tags:

views:

277

answers:

4

I've written a method that returns the milisecond value of a string formatted date, and for some reason it's giving me dates 39000 years in the future. any ideas why?

private long getTimeInMs(String currentStartTimeString) {
     //String newDateString = currentStartTimeString.substring(6,10)+"-"+currentStartTimeString.substring(3, 5)+"-"+currentStartTimeString.substring(0, 2)+ "T" + currentStartTimeString.substring(11);
     String newDateString = currentStartTimeString.substring(0,19);
     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

     long timeInMs;
     try {
      timeInMs = df.parse(newDateString).getTime();
     } catch (ParseException e) {
      log.error("Failed to parse current Start Time",e);
      return 0;
     }
     return timeInMs;
    }

If I enter the date string "2009-07-07 10:51:01.15" it returns 1246960261000 which is actually Wed Aug 06 41484 11:16:40 GMT+0100 (GMT Daylight Time)

Okay I think the issue is that it's giving ms past the Java epoc and I'm evaluating it against the unix epoch...

+4  A: 

It looks fine to me. The Date object that comes out of the parse toString's to "Tue Jul 07 10:51:01 BST 2009" (I'm in the UK timezone here), but that should make no big difference). The millis value of 1246960261000 is correct, why do you think that evaluates to the far future? How did you calculate that?

skaffman
+17  A: 

I'm guessing that you interpreted the returned value from getTime() as if it was a Unix time_t value. It's not - it's milliseconds past the Java epoch, not seconds past the Unix epoch.

Paul Tomblin
The two epochs are the same though I think. All i need to do is divide by 1000.
Omar Kooheji
+1  A: 

running your code in Java 6, i get 1246978261000, which turns out to be correct.

System.out.println(new Date(timeInMs));

returns

Tue Jul 07 10:51:01 EDT 2009

edit:

to confirm others' suggestions that you are looking at seconds (not millis):

System.out.println(new Date(timeInMs*1000));

yields

Mon Mar 02 13:16:40 EST 41485

akf
+1. Try 1246960261000 then 1246960261 on http://www.unixtimestamp.com/index.php
kd304
+1  A: 

The value is correct, in fact :

 (((((1246989061000 / 1000) / 60)/60)/24)/365)

gives

39.54176373033992 years which is about correct given that 0 is 1970.

Alan Moore