0

I've got a problem with date object in IE8, and some older browsers. On website I have input hidden, where I keep date, and after change new date should be in that field.

On my machine everything is fine, but on some others I get NaN-NaN-NaN, that's my code:

var date = new Date($('#curDate').val());
//date.setDate(date.getDate() - 7);
var dateMsg = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
alert(dateMsg);

When I run this file (php), in hidden input I've got Monday's date from the current week 2013-03-25.

This alert return me NaN-N.. on Win XP IE8, and on very old mac, I recon it's problem with object. How to take date value and convert it to object in javascript?

3
  • What date format did you input? Most are not recognised by every browser. Commented Mar 25, 2013 at 16:13
  • 2013-03-25 - YYYY-MM-DD Commented Mar 25, 2013 at 16:14
  • date.js handles a lot of the cross-browser issues with date parsing, btw.. Commented Mar 25, 2013 at 16:29

3 Answers 3

2

Never use new Date(some_string) - it's unreliable because it depends on the user's locale.

Break the string into its yy/mm/dd components yourself and then call new Date(y, m - 1, d)

Sign up to request clarification or add additional context in comments.

4 Comments

The Date constructor uses the local timezone as well.
@Bergi I wasn't talking about timezone, I was talking about mm/dd/yy vs dd/mm/yy
Ah, OK. Yet the OP uses YYYY-MM-DD format - which is never YYYY-DD-MM :-)
his string var uses that, we don't know for certain what's in #curDate
1

Problem with your hyphens..

Convert your hyphens('-') with slashes('/')

var dateStr=$('#curDate').val();
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);

or

var date=new Date(convertToSlash($('#curDate').val()));

    function convertToSlash(string){
      var response = string.replace(/-/g,"/");
      return response;
    }

3 Comments

not sensible advice IMHO - converting to "slash" format does not guarantee locale-independent parsing.
@Alnitak: Dates are nearly always parsed locale-based. To get around that in a cross-browser way, you'd need to use Date.UTC
nb: locales and TZs are not the same thing.
0

You can also use new Date(some_string) format. It's reliable. However, the datestring must be in ISO format that is yyyy/mm/dd.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.