How to get the current UTC time in seconds

swati picture swati · Sep 28, 2011 · Viewed 38.1k times · Source

I have an application, which needs to compare the time in seconds.

I want to know how to get the current UTC time in seconds.

Can some one post an example of it how can we do this in Java?

Answer

Justin King picture Justin King · Sep 28, 2011

You can use this to get timezone passing in timezone you want time back in

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); 

Then you can call whatever you want on the calendar object

System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));

Below example to compare two calendars in seconds

Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

// Set the dates for calendars
cal1.set(2011, 1, 1);
cal2.set(2011, 2, 2);

// Get the represented date in milliseconds as a long
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();

// Calculate difference in milliseconds
long diff = milis2 - milis1;

// Calculate difference in seconds
long diffSecs = diff / 1000;

System.out.println("In seconds: " + diffSecs + " seconds");