繁体   English   中英

使用Java 8 API加上日期的1小时1天

[英]Plus 1 hour and 1 day in date using java 8 apis

我有这段代码可以在Java 8中添加1小时或1天的日期,但是不起作用

    String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(DATE_FORMAT);
    Date parse = format.parse("2017-01-01 13:00:00");
    LocalDateTime ldt = LocalDateTime.ofInstant(parse.toInstant(), ZoneId.systemDefault());
    ldt.plusHours(1);
    ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
    Date te = Date.from(zdt.toInstant());

怎么了? 代码显示:Sun Jan 01 13:00:00 BRST 2017

LocalDateTime是不可变的,并在您调用其上的方法时返回一个新的LocalDateTime。

所以你必须打电话

ldt = ldt.plusHours(1);

除了您不使用日期操作的结果( ldt = ldt.plusHours(1) )的问题外,您实际上并不需要通过LocalDateTime进行此操作。

我将只使用OffsetDateTime,因为您不在乎时区:

OffsetDateTime odt = parse.toInstant().atOffset(ZoneOffset.UTC);
odt = odt.plusDays(1).plusHours(1);
Date te = Date.from(odt.toInstant());

您甚至可以坚持使用Instant

Instant input = parse.toInstant();
Date te = Date.from(input.plus(1, DAYS).plus(1, HOURS));

(带有import static java.time.temporal.ChronoUnit.*;

tl; dr

LocalDateTime.parse(                            // Parse input string that lacks any indication of offset-from-UTC or time zone.
    "2017-01-01 13:00:00".replace( " " , "T" )  // Convert to ISO 8601 standard format.
).atZone(                                       // Assign a time zone to render a meaningful ZonedDateTime object, an actual point on the timeline.  
    ZoneId.systemDefault()                      // The Question uses default time zone. Beware that default can change at any moment during runtime. Better to specify an expected/desired time zone generally.
).plus(
    Duration.ofDays( 1L ).plusHours( 1L )       // Add a span of time.
)

细节

不要将麻烦的旧遗留类DateCalendar与现代java.time类混合使用。 仅使用java.time,避免使用遗留类。

解析和生成字符串时,java.time类默认使用ISO 8601标准格式。 通过将中间的SPACE替换为T转换输入字符串。

String input = "2017-01-01 13:00:00".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

LocalDateTime不代表实际时刻,也不代表时间轴上的一点。 在您指定时区之前,它没有实际意义。

ZoneId z = ZoneId.systemDefault() ;  // I recommend specifying the desired/expected zone rather than relying on current default. 
ZonedDateTime zdt = ldt.atZone( z ) ;

Duration表示未附加到时间轴的时间跨度。

Duration d = Duration.ofDays( 1L ).plusHours( 1L ) ;
ZonedDateTime zdtLater = zdt.plus( d ) ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM