kreya
kreya

Reputation: 1229

Convert time-stamp in to seconds since Unix epoch

How to convert time-stamp in to seconds since Unix epoch? I just convert time-stamp into UTC time-stamp. Now i want to convert this time-stamp into seconds.

Calendar currenttime = Calendar.getInstance();
System.out.println("current: "+currenttime.getTime());

    //TIMESTAMP UTC/GMT
    TimeZone z = currenttime.getTimeZone();
    int offset = z.getRawOffset();
    if(z.inDaylightTime(new Date())){
        offset = offset + z.getDSTSavings();
    }
    int offsetHrs = offset / 1000 / 60 / 60;
    int offsetMins = offset / 1000 / 60 % 60;
    currenttime.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
    currenttime.add(Calendar.MINUTE, (-offsetMins));
    System.out.println("GMT CURRENT TIME: "+currenttime);

Upvotes: 2

Views: 2829

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44844

see http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Date.html#getTime()

It says Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

As per you code

currenttime.getTime().getTime() / 1000

Calendar currenttime = Calendar.getInstance();
System.out.println("current: "+currenttime.getTime());

//TIMESTAMP UTC/GMT
TimeZone z = currenttime.getTimeZone();
int offset = z.getRawOffset();
if(z.inDaylightTime(new Date())){
    offset = offset + z.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
currenttime.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
currenttime.add(Calendar.MINUTE, (-offsetMins));
System.out.println("GMT CURRENT TIME: "+currenttime);

with the addition of

System.out.println("This is : " + currenttime.getTime().getTime() / 1000 + " seconds");

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

Simply divide Java millis by 1000

Upvotes: 0

Related Questions