How to get the current UTC time in seconds
Asked Answered
V

7

13

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?

Valeryvalerye answered 28/9, 2011 at 0:27 Comment(0)
U
17

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");
Unnecessary answered 28/9, 2011 at 0:30 Comment(4)
Thanks Justin for your answer but i want the time in seconds ..I dont see seconds i want in seconds ..thanks...Valeryvalerye
To clarify if I get calendar 1 of 01/01/2011 12:31:21 and calendar 2 of 02/02/2011 07:21:01 that you want the diff in seconds of 20 secs or 3503006104.69374 secsUnnecessary
For seconds: System.out.println(cal.get(Calendar.SECOND)); Just know that this is a number from 0 to 59; you will have to use the whole Calendar object for the comparison.Hardheaded
Thanks a lot to all who answered my questions i really appreciate your time to answer this questions....Valeryvalerye
A
13

System.currentTimeMillis()

Asiaasian answered 28/9, 2011 at 0:29 Comment(6)
This is by the he easiest way to get UTC time in millis (easily convertable to seconds). Unfortunately, the developers of Java recognize that this is not precise enough for doing important calculations with so they recommend using a Calendar object for any date/time calculations or comparisons. Check out download.oracle.com/javase/6/docs/api/java/util/Calendar.htmlHardheaded
currentTimeMillis is not UTC, it's the system local time (which may or may not be UTC).Miscible
@Dunes: Nope, currentTimeMillis is UTC. See the Javadocs: Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. docs.oracle.com/javase/6/docs/api/java/lang/…Caressa
@Caressa you are not correct. The "start of time" is UTC, but the date will be in locale time. You can easily see this by doing: System.out.println(new Date());Seften
@Randgalt: That's because Date.toString() (which you implicitly invoke) is cheating - it prints the date in your local timezone (I have tripped over this, too). The timestamp stored in a Date instance is in UTC. If you have further questions, feel free to ask a separate question :-).Caressa
So, if this is true, why does this not work: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(new Date()); - it shows my local time. If I use the code I posted below to get the current time UTC it works correctly.Seften
C
3
 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();


    }
Chartulary answered 16/5, 2012 at 11:39 Comment(0)
M
3

Joda makes everything simple

import org.joda.time.ReadableInstant;
import org.joda.time.DateTime;

import static org.joda.time.DateTimeZone.UTC;
import static org.joda.time.Seconds.secondsBetween;

...

ReadableInstant start = new DateTime("2011-01-01", UTC);
ReadableInstant end = new DateTime("2011-02-02", UTC);

int secondsDifference = secondsBetween(start, end).getSeconds();
Miscible answered 16/5, 2012 at 12:8 Comment(0)
I
1

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.

Ianiana answered 23/11, 2016 at 11:37 Comment(0)
S
0

To store the date as an integer instead of long, you can divide by 1000 and optionally subtract by another date, such as Jan. 1 2019:

private int getUTC()
{
    Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    cal1.set(2019, 1, 1);
    long millis1 = cal1.getTimeInMillis();

    //Current date in milliseconds
    long millis2 = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());

    // Calculate difference in seconds
    long diff = millis2 - millis1;
    return (int)(diff / 1000);
}
Slack answered 25/1, 2019 at 17:59 Comment(0)
S
-1

This works:

    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    GregorianCalendar gregorianCalendar = new GregorianCalendar
    (
        calendar.get(Calendar.YEAR),
        calendar.get(Calendar.MONTH),
        calendar.get(Calendar.DAY_OF_MONTH),
        calendar.get(Calendar.HOUR_OF_DAY),
        calendar.get(Calendar.MINUTE),
        calendar.get(Calendar.SECOND)
    );
    return gregorianCalendar.getTime();
Seften answered 13/9, 2014 at 15:49 Comment(1)
That's needlessly complicated. Why do copy the values into a new GregorianCalendar? Also, this will lose the milliseconds.Caressa

© 2022 - 2024 — McMap. All rights reserved.