Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix timestamp creation in java [duplicate]

Tags:

java

date

time

Possible Duplicate:
Getting unix timestamp from Date()

I am having the date

Fri, 09 Nov 2012 23:40:18 GMT

and how should I convert it to Unix timestamp like this '1352504418' in java

like image 514
Aravindhan Avatar asked Nov 15 '12 05:11

Aravindhan


2 Answers

First get the date object, then get the time in millisecond(millseconds after 01/01/1970 00:00:00), in the end, divide the milliseconds by 1000 to get the seconds, which is UNIX time. You are done.

e.g.

    String dateString = "Fri, 09 Nov 2012 23:40:18 GMT";
    DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z");
    Date date = dateFormat.parse(dateString );
    long unixTime = (long) date.getTime()/1000;
    System.out.println(unixTime );//<- prints 1352504418
like image 121
Yogendra Singh Avatar answered Oct 17 '22 10:10

Yogendra Singh


Date.getTime provides 'number of milliseconds since January 1, 1970, 00:00:00' which is the same as Unix time * 1000.

like image 11
threenplusone Avatar answered Oct 17 '22 08:10

threenplusone