将字符串yyyy-mm-dd hh:mm:ss + timezone格式化为DateTime [英] Format String yyyy-mm-dd hh:mm:ss +timezone into DateTime
问题描述
我需要格式化一个看起来像这样的字符串:
I need to format a String that looks like this:
"2018-07-20 18:53:46.598000 +02:00:00"
插入这样的DateTime对象:
into a DateTime object like this:
20/07/2018 (HH with Timezone applied):53:46
我的方法是:
String dateTimePattern = "dd/MM/yyyy HH:mm:ss";
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateTimePattern);
Date feUltModDateTime = dateTimeFormat.parse(feUltMod);
feUltMod = feUltModDateTime.toString();
但是我遇到了解析错误:
But I'm getting a parse error:
java.text.ParseException: Unparseable date: "2018-07-20 18:53:46.598000 +02:00:00"
推荐答案
java.time
DateTimeFormatter origFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS XXXXX");
DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss");
ZoneId desiredZone = ZoneId.of("America/Fort_Nelson");
String feUltMod = "2018-07-20 18:53:46.598000 +02:00:00";
OffsetDateTime dateTime = OffsetDateTime.parse(feUltMod, origFormatter);
ZonedDateTime dateTimeWithTimeZoneApplied = dateTime.atZoneSameInstant(desiredZone);
feUltMod = dateTimeWithTimeZoneApplied.format(desiredFormatter);
System.out.println(feUltMod);
此代码段的输出为:
20/07/2018 09:53:46
20/07/2018 09:53:46
通常,您需要两个格式化程序才能将日期或日期时间从一种格式转换为另一种格式:一种指定将转换为的格式,另一种指定将转换为的格式. /em>.
Generally you need two formatters for converting a date or date-time from one format to another: one that specifies the format to convert from and one that specifies the format to convert to.
插入这样的DateTime对象
into a DateTime object like this
日期时间对象没有格式,因此在这方面不能像这样".以上代码段中的dateTimeWithTimeZoneApplied
在指定的时区中,因此小时数也进行了调整.转换到该时区后,我已经按照您提到的格式将其格式化为字符串,以防万一您想要这样做(我不清楚).
A date-time object doesn’t have a format, so in that respect cannot be "like this". dateTimeWithTimeZoneApplied
in the above snippet is in the specified time zone, so has the hours adjusted. After converting to this time zone I have formatted into a string in the format you mentioned, in case you wanted this (I didn’t find it clear).
我正在使用并推荐Java.time,这是现代的Java日期和时间API.您使用的日期和时间类别Date
和SimpleDateFormat
早已过时且设计不当,因此不值得与之抗争.另外,SimpleDateFormat
仅支持毫秒,因此只能在秒上精确到3个小数,而不是6个小数才能正常工作.
I am using and recommending java.time, the modern Java date and time API. The date and time classes you were using, Date
and SimpleDateFormat
, are long outdated and poorly designed, it’s not worth struggling with them. Also SimpleDateFormat
supports only milliseconds so can only work correctly with exactly 3 decimals on the seconds, not with the 6 decimals you have got.
链接: Oracle教程:日期时间解释如何使用java.time
.
这篇关于将字符串yyyy-mm-dd hh:mm:ss + timezone格式化为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!