0

Theres lots of questions about how to convert a timestamp to yyyy-mm-dd but I am trying to do it the other way around.

I have an array of dates in the format 2013-02-25 but I want them to be js timestamps.

I have an array of dates such as ["2013-02-25", "2013-02-22", "2013-02-21"] and ive tried

new Date(dateArray[0]).getTime() / 1000;

but this gives the wrong result as "2013-02-25" is converted to 1361750400 which is Fri, 16 Jan 1970 18:15:50 GMT

any suggestions on how to do this in javascript please?

James
  • 111
  • 2
  • 4
  • 15
  • 1
    What's the relationship between values like `442.80` and a yyyy-mm-dd date? – zneak Apr 02 '13 at 18:18
  • 1
    No. your date comes out as `1361750400000` (3 extra zeroes). that's a proper JS millisecond timestamp. 1361750400 (without the zeroes) is a standard unixtimestamp, which is feb 25th/2013. – Marc B Apr 02 '13 at 18:20
  • sorry i pasted the wrong values, ive edited my question to show the array of dates. Also when I do console.log it outputs 1361750400 so im not sure where the 3 extra zeroes have gone. – James Apr 02 '13 at 18:29
  • 1
    @James You are doing / 1000 , that's where the extra 3 zeros are. – Benjamin Gruenbaum Apr 02 '13 at 18:34
  • Thanks Benjamin, ive been working too long today and my brain is fried. – James Apr 02 '13 at 18:37

1 Answers1

3

Update: Question was updated to use this code for trying to parse dates.

Your problem now is that you do new Date(dateArray[0]).getTime() / 1000; . You shouldn't divide by 1000. Try new Date(dateArray[0]).getTime().


I think the obvious solution is the one you missed :

var date = new Date("2013-02-25")// contains Mon Feb 25 2013 02:00:00 
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • @Kyle Thanks, though actually if you're going to add an MDN link might be the one that describes what the constructor is doing: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/parse – Benjamin Gruenbaum Apr 02 '13 at 18:21
  • `Date.parse()` is a method of the `Date` global object, not a constructor. – Kyle Apr 02 '13 at 18:24
  • @Kyle Date.parse is how the constructor accepting a date string works :) – Benjamin Gruenbaum Apr 02 '13 at 18:33
  • I see what you mean. Is firefox 4 the only browser that supports that subset of ISO-8601? Or do other browsers support it? – Kyle Apr 02 '13 at 18:42