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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25991892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:35:17  来源:igfitidea点击:

How do I format time to UTC time zone?

scala

提问by user626528

I have some date/time in a Date object; how can I format it to a string, so it represents appropriate date/time in UTCtime zone?

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

回答by Andrzej Jozwik

I'm in central europe TZ. It is my code with joda-time:

我在中欧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:

爪哇8:

Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_20).

欢迎使用 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]

回答by Daniel Olszewski

The solution without Joda Time:

没有 Joda Time 的解决方案:

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