Date 几乎完全被废弃了,因为向下兼容的原因仍然存在。如果需要设置特定的日期或进行日期算术,请使用 日历:
Calendar calendar = Calendar.getInstance(); // gets a calendar using the default time zone and locale.
calendar.add(Calendar.SECOND, 5);
System.out.println(calendar.getTime());
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime then = now.plusSeconds( 5 );
Interval interval = new Interval( now, then );
Period period = interval.toPeriod( );
DateTime thenAgain = now.plus( period );
转到控制台。
System.out.println( "zone: " + zone );
System.out.println( "From now: " + now + " to then: " + then );
System.out.println( "interval: " + interval );
System.out.println( "period: " + period );
System.out.println( "thenAgain: " + thenAgain );
跑步的时候。
zone: America/Montreal
From now: 2015-06-15T19:38:21.242-04:00 to then: 2015-06-15T19:38:26.242-04:00
interval: 2015-06-15T19:38:21.242-04:00/2015-06-15T19:38:26.242-04:00
period: PT5S
thenAgain: 2015-06-15T19:38:26.242-04:00
Date now = new Date();
System.out.println(now);
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.SECOND, 5);
now = c.getTime();
System.out.println(now);
// Output
Tue Jun 11 16:46:43 BDT 2019
Tue Jun 11 16:46:48 BDT 2019
Instant // Use modern `java.time.Instant` class to represent a moment in UTC.
.now() // Capture the current moment in UTC.
.plusSeconds( 5 ) // Add five seconds into the future. Returns another `Instant` object per the Immutable Objects pattern.