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?
Current UTC timestamp to time is 22:02:52.
Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Calling the method from any time zone returns the same UTC timestamp.
How to get the current epoch time in ... long epoch = System.currentTimeMillis()/1000; Returns epoch in seconds.
By convention, meteorologists use just one time zone: Universal Time, Coordinated (UTC). They also use the twenty four hour clock (where 0000 = midnight UTC). The date/time stamp on each forecast image represents the time at which the forecast is valid, measured in UTC.
public static long getUtcTime(long time) {
System.out.println("Time="+time);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dbefore=new Date(time);
System.out.println("Date before conversion="+format.format(dbefore));
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
TimeZone timezone = c.getTimeZone();
int offset = timezone.getRawOffset();
if(timezone.inDaylightTime(new Date())){
offset = offset + timezone.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
System.out.println("offset: " + offsetHrs);
System.out.println("offset: " + offsetMins);
c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));
System.out.println("Date after conversion: "+format.format(c.getTime()));
System.out.println("Time converted="+c.getTime().getTime());
return c.getTime().getTime();
}
Get current UTC time in seconds (since 1.5) :
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
according to Javadoc:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#currentTimeMillis
Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With