6

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

Iota
  • 15
  • 5
Aravindhan
  • 3,566
  • 7
  • 26
  • 42

2 Answers2

14

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
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • if your unix time is going to be used later to get the date back from it (e.g. by Front End - JavaScript date constructor) then don't divide by 1000. it will make things complicated. – CodeGems Jul 24 '17 at 03:17
11

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

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
threenplusone
  • 2,112
  • 19
  • 28