I am looking at the Date documentation and trying to figure out how I can express NOW + 5 seconds. Here\'s some pseudocode:
import java.util.Date
public clas
UPDATE: See my new Answer using java.time classes. I am leaving this Answer intact as history.
The Answer by Pascal Thivent and the Answer by Jon Skeet are both correct and good. Here's a bit of extra info.
PT5S
(ISO 8601)Another way to express the idea of "five seconds later" is in a string using the standard formats defined by ISO 8601. The duration/period format has this pattern PnYnMnDTnHnMnS
where the P
marks the beginning and the T
separates the date portion from time portion.
So five seconds is PT5S
.
The Joda-Time 2.8 library can both generate and parse such duration/period strings. See the Period, Duration, and Interval classes. You can add and subtract Period objects to/from DateTime objects.
Search StackOverflow for many examples and discussions. Here's one quick example.
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 );
Dump to console.
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 );
When run.
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