My program uses LocalDateTime and the value is always in UTC.
LocalDateTime根本没有时区,因此它不是UTC.
在UTC中,请使用Instant类.这表示时间线上的时刻,分辨率高达纳秒.
Instant now = Instant.now();
要调整到时区,请应用ZoneId以获取ZonedDateTime.
切勿使用像PST& amp; PDT在主流媒体中如此常见.它们不是实时区域,不是标准化的,甚至不是唯一的(!).在大陆/地区格式中使用proper time zone names.
ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = instant.atZone( zoneId );
听起来你的数据接收器的设计很糟糕,输入一个字符串,表示假设在America / Los_Angeles时区的日期时间值,但没有任何指示符(没有偏离UTC,没有时区).
要获得这样的字符串,缺少任何偏移量或区域,请使用名为ISO_LOCAL_DATE_TIME的预定义DateTimeFormatter.您将获得标准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 );