JSON Stringify Changes Time of Date Because of Utc

JSON Stringify changes time of date because of UTC

Recently I have run into the same issue. And it was resolved using the following code:

x = new Date();
let hoursDiff = x.getHours() - x.getTimezoneOffset() / 60;
let minutesDiff = (x.getHours() - x.getTimezoneOffset()) % 60;
x.setHours(hoursDiff);
x.setMinutes(minutesDiff);

How to JSON stringify a javascript Date and preserve timezone

Assuming you have some kind of object that contains a Date:

var o = { d : new Date() };

You can override the toJSON function of the Date prototype. Here I use moment.js to create a moment object from the date, then use moment's format function without parameters, which emits the ISO8601 extended format including the offset.

Date.prototype.toJSON = function(){ return moment(this).format(); }

Now when you serialize the object, it will use the date format you asked for:

var json = JSON.stringify(o);  //  '{"d":"2015-06-28T13:51:13-07:00"}'

Of course, that will affect all Date objects. If you want to change the behavior of only the specific date object, you can override just that particular object's toJSON function, like this:

o.d.toJSON = function(){ return moment(this).format(); }

JSON.stringify changes date

The JSON.stringify method stored the date as UTC in the string, and when you parse that in .NET you will get a DateTime that contains the exact same point in time, but converted to the local time of the server.

You can handle this in two ways, you can either convert the time back to the original time zone, or you can avoid using the Date data type.

Converting to the original time zone of course requires you to know what the time zone is. Example:

var zone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime userTime = TimeZoneInfo.ConvertTimeFromUtc(date.ToUniversalTime(), zone);

To avoid using the Date type, you would format the date into a string before serialising it. Example:

var s = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();

On the server side you would parse the string using the same format:

DateTime userTime = DateTime.ParseExact(date, "yyyy-M-d", CultureInfo.InvariantCulture);

Json Stringify date produces a wrong date compared to javascript date

This is due to the timezone component in the Date. The work around I did was:

var date = $(.datepicker).datepicker('getDate');
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()))
var result = Json.stringify(utcDate);

The removes the timezone component.

The date changing to one day before while converting JavaScript Date object to a JSON string

Because your date string is in a non-standard format, the Date constructor treats it as a local time (see the manual for Date.parse() in the section "Differences in assumed time zone"). However, JSON.stringify() calls Date.toJSON() which calls Date.toISOString() which always outputs the time with a zero UTC offset. As a result, you need to translate your date to UTC by subtracting the timezone offset, which can be obtained via Date.getTimezoneOffset().

Alternatively, provide an ISO format (YYYY-MM-DD) date string and no adjustment is required as the Date constructor will treat that as a UTC time.

// non-standard date formatvar newDate = new Date('12/01/19');console.log(newDate.toJSON());
var os = newDate.getTimezoneOffset();newDate = new Date(newDate.getTime() - os * 60 * 1000);console.log(newDate.toJSON());
// ISO format datevar newDate2 = new Date('2019-12-01');console.log(newDate2.toJSON());

How do i tell javascript to not convert date object to UTC while serializing

The best way to handle this is to write a replacer function and pass that to JSON.stringify. The replacer would detect dates and output the format you want for them.

JSON.stringify(new Date(), function(key, value) {
var rawValue = this[key];
if (rawValue instanceof Date) {
return /*...whatever format you want using `rawValue`...*/;
}
return value;
});

There I've made it an inline function, but of course you can make it a named function that you reuse.

Example:

console.log(JSON.stringify(new Date(), function(key, value) {  var rawValue = this[key];  if (rawValue instanceof Date) {    return "Your string here for " + rawValue;  }  return value;}));


Related Topics



Leave a reply



Submit