Javascript: How To Parse Date From Utc String And Offset?
Solution 1:
Is that what you need ?
const moment = require('moment');
moment
.utc('2013-06-20T07:00:00.427')
.zone(-360)
.format();
here you'll find a lot of displaying options -> http://momentjs.com/docs/#/displaying/
or maybe just:
constdate = newDate('2017-10-01T12:00:00.000Z');date.setMinutes(-360);
date.toISOString();
Solution 2:
I guess that the timestamp "2017-10-01T12:00:00.000Z" is correct and that the offset of 360 is really -360 (since you say it should really be US Central Standard Time of -0600).
It can be assumed the offset does not include for daylight savings time.
Offsets never consider daylight saving, they are absolute values. Daylight saving changes the offset for a region within a timezone, usually reflected by also changing the timezone name (e.g. Central Standard Time to Central Daylight Time).
Anyway, if the original value is always UTC and you want to display it in the original timezone, you can parse the original UTC date to a Date, adjust the UTC time value, then use toISOString (which is always UTC) and append the appropriate offset designator. You also have to flip the sign of the offset.
The following does all that and avoids the built-in parser, don't be tempted to use it:
// Offset has opposite sign: 360 == -0600var data = {date: "2017-10-01T12:00:00.000Z",
offset: 360};
/* Return a timestamp adjusted for offset
** @param {object} data - object with the following properties
** date: ISO 8601 format date and time string with Z offset
** offset: offset in minutes +ve west, -ve east
** @returns {string} ISO 8601 timestamp in zone
*/functionformatDate(data) {
// Pad single digits with leading zerofunctionpad(n){return (n<10? '0' : '') + n}
// Format offset: 360 => -0600functionformatOffset(offset) {
var sign = offset < 0? '+' : '-'; // Note sign flip
offset = Math.abs(offset);
return sign + pad(offset/60|0) + pad(offset%60);
}
// Parse ISO 8601 date and time string, assume UTC and valid, ms may be missingfunctionparseISO(s) {
var b = s.split(/\D/);
returnnewDate(Date.UTC(b[0],--b[1],b[2],b[3],b[4],b[5],b[6]|0));
}
var d = parseISO(data.date);
var offset = data.offset;
d.setUTCMinutes(d.getUTCMinutes() - offset);
return d.toISOString().replace(/z$/i, formatOffset(offset));
}
console.log(formatDate(data));
Post a Comment for "Javascript: How To Parse Date From Utc String And Offset?"