Roland
Roland

Reputation: 18415

How to specify a date / time offset in days

Using Java's date parsing mechanism I'd like to specify a date / time with an offset in days. Basically similar to the timezone offset.

Examples:

Is that possible and how?

Upvotes: 2

Views: 1114

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

I don't think it is possible at the time of the parsing. But still you can do date time manipulations in Java8 after parsing it to a LocalDateTime object like so,

System.out.println("Tomorrow: " + LocalDateTime.now().plusDays(1));
System.out.println("Yesterday: " + LocalDateTime.now().minusDays(1));
System.out.println("One week ago: " + LocalDateTime.now().minusWeeks(1));

You can apply date and time modifications in combination with the Duration class. Example:

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime now = LocalDateTime.now();
Duration duration = Duration.parse( "-P1DT15M");

System.out.println( "Duration   : " + duration.toMillis());
System.out.println( "Now        : " + formatter.format( now));
System.out.println( "Now-P1DT15M: " + formatter.format( duration.addTo(now)));

results in

Duration   : -87300000
Now        : 2018-04-12T08:59:10.91
Now-P1DT15M: 2018-04-11T08:44:10.91

Upvotes: 3

Related Questions