如何将时间格式化为UTC时区?

时间:2014-09-23 09:46:04

标签: scala

我在Date对象中有一些日期/时间;如何将其格式化为字符串,以便在 UTC 时区中表示适当的日期/时间?

2 个答案:

答案 0 :(得分:13)

我在中欧TZ。这是我的代码与joda-time:

scala> val myTz = DateTimeZone.getDefault()
myTz: org.joda.time.DateTimeZone = Europe/Warsaw

scala> val now = new Date()
now: java.util.Date = Tue Sep 23 12:06:05 CEST 2014

scala> val utcString = new DateTime(now).withZone(DateTimeZone.UTC).toString()
utcString: String = 2014-09-23T10:06:05.302Z

Java 8:

欢迎使用Scala版本2.11.2(Java HotSpot(TM)64位服务器VM,Java 1.8.0_20)。

scala>  import java.time._
import java.time._

scala> val utcZoneId = ZoneId.of("UTC")
utcZoneId: java.time.ZoneId = UTC

scala> val zonedDateTime = ZonedDateTime.now
zonedDateTime: java.time.ZonedDateTime = 2014-09-24T09:45:31.165+02:00[Europe/Warsaw]

scala> val utcDateTime = zonedDateTime.withZoneSameInstant(utcZoneId)
utcDateTime: java.time.ZonedDateTime = 2014-09-24T07:45:31.165Z[UTC]

答案 1 :(得分:5)

没有Joda时间的解决方案:

val date = new Date()
val format = new SimpleDateFormat()
format.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"))
val dateAsString = format.format(date)