Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current UTC time in seconds

Tags:

java

time

seconds

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?

like image 916
swati Avatar asked Sep 28 '11 00:09

swati


People also ask

What is current UTC time in seconds?

Current UTC timestamp to time is 22:02:52.

How do I find my UTC timestamp?

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 do you find the timestamp in seconds?

How to get the current epoch time in ... long epoch = System.currentTimeMillis()/1000; Returns epoch in seconds.

What is timestamp UTC?

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.


2 Answers

 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();


    }
like image 65
himb2001 Avatar answered Sep 19 '22 14:09

himb2001


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.

like image 28
Aure77 Avatar answered Sep 18 '22 14:09

Aure77