我的程序使用 LocalDateTime 并且该值始终采用 UTC。
A LocalDateTime
根本没有时区,所以它是not以世界标准时间 (UTC) 表示。
对于 UTC 时间,请使用Instant https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html班级。这代表了时间线上的一个时刻,分辨率高达纳秒。
Instant now = Instant.now();
要调整到时区,请应用ZoneId
得到一个ZonedDateTime
.
切勿使用 3-4 个字母的缩写,例如PST
& PDT
因此在主流媒体上屡见不鲜。它们不是实时时区,不是标准化的,甚至不是唯一的(!)。使用正确的时区名称 https://en.m.wikipedia.org/wiki/List_of_tz_database_time_zones in continent/region
format.
ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = instant.atZone( zoneId );
听起来您的数据接收器的设计很糟糕,无法输入表示日期时间值的字符串assumed将在America/Los_Angeles
时区但缺少任何指示符(没有与 UTC 的偏移量,没有时区)。
要获得这样一个缺少任何偏移量或区域的字符串,请使用预定义的DateTimeFormatter http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html named ISO_LOCAL_DATE_TIME http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME。你会得到一个标准的字符串ISO 8601 https://en.m.wikipedia.org/wiki/ISO_8601格式如下:2011-12-03T10:15:30
.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME );
您的数据接收器忽略了T
从中间开始,所以用 SPACE 替换。
output = output.replace( `T` , " " );
如果您的数据接收器只需要整秒,您可以截断日期时间值中的任何小数秒。
zdt = zdt.truncatedTo( ChronoUnit.SECONDS );
走向另一个方向,从字符串到对象,定义一个格式化程序,解析为LocalDateTime
并应用假定的时区。
String input = "2011-12-03 10:15:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss" );
LocalDateTime ldt = LocalDateTime.parse( input , formatter );
ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = ldt.atZone( zoneId );