How to find the difference between two dates in seconds in different time zones

I have a piece of code that finds the difference between two dates (in the format yyyy-MM-dd hh: mm: ss). This code runs on several servers around the world. One of the two dates is the current time in the specific time zone in which the code is executed (server time), and the other is the time received from the database. if the difference between the two times exceeds 86400 seconds (1 day), then it should print “invalid”, otherwise “valid” should be printed. The problem that the code encounters is that I run it on my local computer, it is operational, but when I deploy it on a server in the USA, it takes into account GMT time, not local time. Wherever the code runs, I want the difference between the current time and the time received from the database, and if it exceeds 86400 seconds,I want to print invalid. How to achieve this in java? PS: I tried the Date object, but considered GMT only everywhere.

+3
source share
3 answers

I would use GMT everywhere and only convert to local time for display.

To find the difference, convert both times to the same time zone (say GMT) and accept the difference.

+5
source

You can do this with the code below.

Date date = new Date();

DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));

Date date1 = dateformat.parse(formatter.format(date));

// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));

Date date2 = dateformat.parse(formatter.format(date)); 
// Prints the date in the IST timezone
//    System.out.println(formatter.format(date));

Now compare date1 with date2

+2
source

-, . , .

, getTime(), . 1 86400 * 1000 . , , / .

, .

0

All Articles