16

I have a senario where i have to parse two dates for example start date and end date.

var startdate = '02/01/2011';
var enddate = '31/12/2011';

But if we alert start date

 alert(Date.Parse(startdate)); i will get 1296498600000

but if i alert enddate

 alert(Date.Parse(enddate)); i will get NaN

But this is working in other browsers except Chrome, But in other browsers

alert(Date.Parse(enddate)); i will get 1370889000000

Can anybody know a workaround for this?

Febin J S
  • 1,358
  • 3
  • 26
  • 53

2 Answers2

12

If you want to parse a date without local differences, use the following, instead of Date.parse():

var enddate = '31/12/2011'; //DD/MM/YYYY
var split = enddate.split('/');
// Month is zero-indexed so subtract one from the month inside the constructor
var date = new Date(split[2], split[1] - 1, split[0]); //Y M D 
var timestamp = date.getTime();

See also: Date

CatBusStop
  • 3,347
  • 7
  • 42
  • 54
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • This helps me a lot in resolving, Thanks Rob – Febin J S Nov 01 '11 at 11:35
  • Thanks, hit a similar bug and you saved me, +1 – iamserious Jan 10 '12 at 11:28
  • Careful using this - it's just caught me out as months appear to be 0 indexed for some strange reason... var date = new Date(split[2], parseInt(split[1] - 1), split[0]); worked though. – CatBusStop Jul 30 '12 at 14:29
  • It certainly appeared to be dd/mm/yyyy - using this with 28/06/2012 then showing the date in an alert gave me 28th Jul 2012 :S – CatBusStop Jul 30 '12 at 14:36
  • @TomAllen Oops, I misunderstand your first comment. I thought that you meant that month was at index zero of the `split` array. The month starts counting at index zero indeed, see [MDN: `Date`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/#Parameters). – Rob W Jul 30 '12 at 20:42
2

According to this

dateString A string representing an RFC822 or ISO 8601 date.

I've tried your code and I also get NaN for the end date, but if i swap the date and month around, it works fine.

Connell
  • 13,925
  • 11
  • 59
  • 92