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?

Community
  • 1
  • 1
swati
  • 2,099
  • 6
  • 19
  • 23

7 Answers7

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");
Justin King
  • 1,428
  • 12
  • 14
  • Thanks Justin for your answer but i want the time in seconds ..I dont see seconds i want in seconds ..thanks... – swati Sep 28 '11 at 00:46
  • 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 secs – Justin King Sep 28 '11 at 00:53
  • 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. – Jesse Webb Sep 28 '11 at 01:14
  • Thanks a lot to all who answered my questions i really appreciate your time to answer this questions.... – swati Sep 28 '11 at 20:23
13

System.currentTimeMillis()

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • 1
    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 http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html – Jesse Webb Sep 28 '11 at 01:13
  • 6
    currentTimeMillis is not UTC, it's the system local time (which may or may not be UTC). – Dunes May 16 '12 at 11:51
  • 5
    @Dunes: Nope, `currentTimeMillis` is UTC. See the Javadocs: _Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC._ http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#currentTimeMillis%28%29 – sleske Nov 01 '12 at 23:36
  • 1
    @sleske 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());` – Randgalt Sep 13 '14 at 15:39
  • 4
    @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 :-). – sleske Sep 14 '14 at 12:11
  • Interesting! Thanks. I'll re-check this. – Randgalt Sep 15 '14 at 13:46
  • 1
    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. – Randgalt Sep 17 '14 at 00:06
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();


    }
himb2001
  • 1,371
  • 1
  • 10
  • 7
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();
SomeGuyOnAComputer
  • 5,414
  • 6
  • 40
  • 72
Dunes
  • 37,291
  • 7
  • 81
  • 97
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.

Aure77
  • 3,034
  • 7
  • 33
  • 53
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);
}
live-love
  • 48,840
  • 22
  • 240
  • 204
-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();
Randgalt
  • 2,907
  • 1
  • 17
  • 31
  • That's needlessly complicated. Why do copy the values into a new GregorianCalendar? Also, this will lose the milliseconds. – sleske Dec 24 '14 at 20:33