Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda Api handle Time Zone for isBeforeNow isAfterNow comparision

I want to check if a given DateTime is before or after current DateTime. I was converting input time and current time to a common time zone (say UTC) and comparing DateTime. But I stumbled upon Joda Api, hence I was curious to know if Joda is capable of doing this without a time zone conversion. Example:

clientDateTime.isBeforeNow()
like image 208
AkD Avatar asked Feb 18 '23 04:02

AkD


1 Answers

Yes, Joda DateTime comparisons with current time do not require a time zone conversion.

When comparing with current time, such as DateTime.isBeforeNow and DateTime.isAfterNow, Joda simply compares the underlying absolute milliseconds since Jan 1, 1970. The same instant in time has exactly the same absolute milliseconds value, regardless of the timezone.

For example, the instant 1355625068295 corresponds to:

DateTime dt = new DateTime(1355625068295L);

DateTime utc = dt.withZone(DateTimeZone.UTC);
DateTime ny = dt.withZone(DateTimeZone.forID("America/New_York"));
DateTime tk = dt.withZone(DateTimeZone.forID("Asia/Tokyo"));

System.out.println(utc.getMillis() + " is " + utc);
System.out.println(ny.getMillis() + " is " + ny);
System.out.println(tk.getMillis() + " is " + tk);

Output:

1355625068295 is 2012-12-16T02:31:08.295Z
1355625068295 is 2012-12-15T21:31:08.295-05:00
1355625068295 is 2012-12-16T11:31:08.295+09:00

And when comparing with "now":

System.out.println("now: " + new DateTime().getMillis());
System.out.println(ny.isBeforeNow());
System.out.println(ny.plusHours(1).isAfterNow());
System.out.println(tk.isBeforeNow());
System.out.println(tk.plusHours(1).isAfterNow());

Output:

now: 1355625752323
true
true
true
true
like image 111
cambecc Avatar answered Apr 25 '23 15:04

cambecc