[英]How to convert date format to UTC in Scala?
How to convert date format "2021-02-28 13:38:00.597+0000"
to "Mon, Feb 28,2021 15:25:00 UTC"
UTC format in Scala?如何在 Scala 中将日期格式
"2021-02-28 13:38:00.597+0000"
转换为"Mon, Feb 28,2021 15:25:00 UTC"
UTC 格式?
If you could use java.time
, you would need如果你可以使用
java.time
,你需要
DateTimeFormatter
for parsing String
s with the format of your input example, which is quite near to ISO standard, but is missing the 'T'
between date and time of dayDateTimeFormatter
用于使用输入示例的格式解析String
s,它非常接近 ISO 标准,但缺少日期和时间之间的'T'
DateTimeFormatter
for outputting the temporal content in the desired format, which includes (English) abbreviations for day of week and month of yearDateTimeFormatter
用于以所需格式输出时间内容,其中包括(英文)星期几和一年中月份的缩写OffsetDateTime
for parsing the String
with the first DateTimeFormatter
andDateTimeFormatter
解析String
的OffsetDateTime
和ZonedDateTime
for the temporal value in UTC ZonedDateTime
This is how I would do it in Java:这就是我在 Java 中的做法:
public static void main(String[] args) {
// example String
String utcDatetimeString = "2021-02-28 13:38:00.597+0000";
// prepare a formatter that can parse a String of this format
DateTimeFormatter dtfIn = DateTimeFormatter.ofPattern(
"uuuu-MM-dd HH:mm:ss.SSSxxxx",
Locale.ENGLISH
);
// parse it to an OffsetDateTime
OffsetDateTime odt = OffsetDateTime.parse(utcDatetimeString, dtfIn);
// then convert it to a ZonedDateTime applying UTC zone
ZonedDateTime zdt = odt.atZoneSameInstant(ZoneId.of("UTC"));
// prepare a formatter that produces the desired output
DateTimeFormatter dtfOut = DateTimeFormatter.ofPattern(
"EEE, MMM dd, uuuu HH:mm:ss zzz",
Locale.ENGLISH
);
// and print the ZonedDateTime using the formatter
System.out.println(zdt.format(dtfOut));
}
Output: Output:
Sun, Feb 28, 2021 13:38:00 UTC
You can use the DateTimeFormat from joda-time.您可以使用来自 joda-time 的DateTimeFormat 。 You have not mentioned a time zone at all, and using my time zone would give a different hour, so I used UTC for the first date as well.
您根本没有提到时区,使用我的时区会给出不同的时间,所以我也使用 UTC 作为第一个日期。 You can adjust that to your time zone:
您可以将其调整为您的时区:
val OldFormat = "yyyy-MM-dd HH:mm:ss.SSSZ"
val NewFormat = "EEE, MMM dd,yyyy HH:mm:ss z"
val oldDateString = "2021-02-28 13:38:00.597+0000"
val formatterOld = DateTimeFormat.forPattern(OldFormat)
val formatterNew = DateTimeFormat.forPattern(NewFormat)
val dateTime = formatterOld.withZoneUTC().parseDateTime(oldDateString)
val newDateString = formatterNew.withZoneUTC().print(dateTime)
println(dateTime) // 2021-02-28T13:38:00.597Z
println(newDateString) // Sun, Feb 28,2021 13:38:00 UTC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.