17
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scala: joda-timeで日付をyyyy-MM-dd HH:mm:ss形式にフォーマットしたい

Posted at

Scalaでjoda-timeライブラリを用いて、現在日時をyyyy-MM-dd HH:mm:ss形式で整形する方法。
MySQLのDATETIME型に保存する際の変換などに使う。

import org.joda.time.DateTime
import org.joda.time.format._

val dateTime = new DateTime()
// dateTime: org.joda.time.DateTime = 2014-10-30T09:29:29.899Z

val dateString = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").print(dateTime)
// dateString: String = 2014-10-30 09:28:09

上の例では実行環境のタイムゾーンになる。UTCでフォーマットしたい場合は、タイムゾーンをUTCに指定したDateTimeオブジェクトを渡す。

import org.joda.time.DateTime
import org.joda.time.format._
import org.joda.time.DateTimeZone

val dateTime = new DateTime()
// dateTime: org.joda.time.DateTime = 2014-10-30T09:30:11.634Z

val dateString = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").print(dateTime.withZone(DateTimeZone.UTC))
// dateString: String = 2014-10-30 09:30:11

なお、joda-timeを使うためには、build.sbt の libraryDependenciesjoda-timejoda-convert を書いておく。

build.sbt
libraryDependencies ++= Seq(
  "joda-time" % "joda-time" % "2.3",
  "org.joda" % "joda-convert" % "1.6"
)
17
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?