Is there a way where we can detect/convert an incoming variable of type/format of UTC or Moment JS Object or Date()
object or a plain string containing datetime
, to a common format of Moment JS object?
Example:
"1509760983",
Date 2017-10-10T02:20:10.570Z,
Object { _isAMomentObject: true, _isUTC: false, _locale: Object, _d: Date 2017-11-04T02:17:33.747Z, _z: null },
"Sat, 04 Nov 2017 02:03:03 GMT",
"2017-11-04T02:20:14.896Z"
My hack:
var offset = moment().utcOffset();
momentObj = moment(variable).utcOffset(offset);
I was able to convert all other formats to Moment JS without any "deviation" in the data, except if the variable is already a Date()
object.
var offset = moment().utcOffset();
momentObj = (variable instanceof Date) ? moment(variable) : moment(variable).utcOffset(offset);
Note: Since a Date()
object can only be generated in the browser, so there is no need to add offset to convert the time to local timezone.
Is there a better (fail-safe) approach to this solution?
The last char of the javascript date "Z" shows that the object's timezone is set to UTC (Z time, zulu time). You are getting thè correct timezone. If you want to convert the timezone to the local one, you should use moment timezone plugin with moment.js.
Then you would do:
momentObj = moment(variable).tz(moment.tz.guess());
to convert/set all moment objects to the user's timezone.