3

the below code returns one day earlier,

var myJSON = JSON.stringify(new Date("02/02/1997"));
alert(myJSON);

myJSON variables returns "1997-02-01T18:30:00.000Z"

Why its returning wrong value.

Here, what does the meaning of "T18:30:00.000Z"

Is there any other way of converts the Date object to the String.

Kalai
  • 287
  • 1
  • 5
  • 17
  • 4
    Its converting local Date object to UTC date – Satpal Feb 13 '17 at 04:48
  • Try JSON.stringfy(new Date("02/02/1997").toDateString()); – Alf Moh Feb 13 '17 at 04:52
  • what you're trying to achieve, your original data seems to be a string "02/02/1997"? – cur4so Feb 13 '17 at 04:54
  • It's not the wrong date. If your timezone offset is +05:30 it's the correct date and transferable to any other system. Probably a duplicate of [*Where can I find documentation on formatting a date in JavaScript?*](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript?s=1|4.5819) – RobG Feb 13 '17 at 09:38
  • Possible duplicate of [JSON Stringify changes time of date because of UTC](http://stackoverflow.com/questions/1486476/json-stringify-changes-time-of-date-because-of-utc) – Debug Diva Feb 13 '17 at 12:34

3 Answers3

2

Try this..

    var myJSON = JSON.stringify(new Date("02/02/1997").toLocaleString());
    alert(myJSON);
Sankar
  • 6,908
  • 2
  • 30
  • 53
Dee_wab
  • 1,171
  • 1
  • 10
  • 23
  • Even if parsing the string produces the correct date (which is problematic), the result of *toLocaleString* is entirely implementation dependent and the string produced by one host may not be parsed correctly by another. – RobG Feb 13 '17 at 09:37
0

It is converting your Date object to UTC date.

You should convert Date object to String value using predefined methods of Date Object. Like:

JSON.stringify(new Date("02/02/1997").toLocaleString());

JSON.stringify(new Date("02/02/1997").toDateString()); // to get date portion
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
  • No, don't do that. Parsing a string like "02/02/1997" is not a good idea. Also, the result of *toLocaleString* is entirely implementation dependent and the string created by one host may not be parseable by another. – RobG Feb 13 '17 at 09:36
-3

Recommend you take a look at moment.js. The framework provides a very nice API for:

Parse, validate, manipulate, and display dates in JavaScript.

Convert your date into the desired string format and then JSON.stringify.

Ben Crowhurst
  • 8,204
  • 6
  • 48
  • 78
  • 1
    I don't think suggesting a library is appropriate for answering a question about JavaScript's standard library – PaulBGD Feb 13 '17 at 05:00
  • 2
    Given the endless fun of JavaScript date handling thought I'd drop it in to the conversation. Sorry for the static. – Ben Crowhurst Feb 13 '17 at 05:01
  • I totally agree that moment.js is great, it's just not something that's relevant as to how JavaScript's standard library works. – PaulBGD Feb 13 '17 at 05:02