Reputation: 21137
I am converting a Data Object to JSON and back with JSON.stringify
and JSON.parse
.
This works great, on all devices but on Samsung Galaxy SII where for the line:
console.log(jsonObj.gebDat+"::"+new Date(jsonObj.gebDat));
I get the output:
1973-07-01T10:49:25.134Z::Invalid Date
I am implementing this exactly like at this answer, and it works for most devices, am I doing something wrong??
UPDATE
to clarify the question. I create a String calling
var stringToSave = JSON.stringify({gebDat: dataclass.gebDat, <here are some more variables>});
then I save it. Later, I load the string and parse it with
var jsonObj = JSON.parse(stringToSave);
then, I try to set my date again (calling a log just before that line) with
console.log(jsonObj.gebDat+"::"+new Date(jsonObj.gebDat));
this.gebDat = new Date(jsonObj.gebDat);
The log gives me the invalid date as shown above, and when I represent the Date it displays NaN.NaN.NaN
instead of the expected 01.07.1973
Upvotes: 1
Views: 745
Reputation: 1
you need send string and you send callback.
try:
console.log(jsonObj.gebDat+"::"+new Date(jsonObj.gebDat()));
Upvotes: 0
Reputation: 15566
1.Date string formats are implementation dependent. It is always recommended to use timestamps when you save dates.
var timestamp = Date.parse( new Date() );//1372675910000
Now you can use the saved timestamps to recreate the date later
var date = new Date(1372675910000);//Mon Jul 01 2013 16:21:50 GMT+0530 (India Standard Time)
2.For a simple transition from your current solution, in case you dont handle different timezones,
var dateString = jsonObj.getDat.substring(0,23);
var datePart = dateString.split('T')[0].split('-');
var timePart = dateString.split('T')[1].split(/[:.]/);
var DateOj = new Date(datePart[0], datePart[1], datePart[2], timePart[0], timePart[1], timePart[2]);
Let me clarify 1, with reference to your update.
var stringToSave = JSON.stringify({gebDat: Date.parse(dataclass.gebDat), <here are some more variables>});
var jsonObj = JSON.parse(stringToSave);
console.log('timestamp :' + jsonObj.gebDat);//1372680083000
console.log(new Date(jsonObj.gebDat));//Mon Jul 01 2013 17:31:23 GMT+0530 (India Standard Time)
Upvotes: 1