0

I have a string 2021-04-07T13:51:39.664+11:00 which I use to create a Date object: d = new Date('2021-04-07T13:51:39.664+03:00').

After that, d is an instance to represent the date time. Now I'd like to get the timezone offset from d, but d.getTimezoneOffset() always return local timezone offset which is -600 in my case. How can I get the timezone offset from the string? Does it get lost when I build the date instance? Do I have to parse the string to get it?

If I have a date object, how can I generate a string with the offset at the end: 2021-04-07T13:51:39.664+03:00? toISOString() only generate UTC time.

I know moment is a good date library but I don't want to add this dependency since it is too large.

Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523

3 Answers3

0

function dateZ(dateString) {
    var _date = dateString.substring(0, 23);
    var _offset = dateString.substring(23);
    var _dateValue = new Date(dateString);
    function offset(value) {
        if (value) {
            _offset = value;
            _dateValue = new Date(toString());
        }
        return _offset;
    }
    function date(value) {
        if (value) {
            _date = value;
            _dateValue = new Date(toString());
        }
        return _dateValue;
    }
    function toString() {
        return `${_date}${_offset}`
    }
    return { offset, date, toString };
}

var d = dateZ('2021-04-07T13:51:39.664+03:00');
console.log(d.date(), d.offset(), d.toString());
d.offset('+05:30');
console.log(d.date(), d.offset(), d.toString());
Wazeed
  • 1,230
  • 1
  • 8
  • 9
0

This is probably not the best possible approach, but it is portable and quite useful if you are in control of the application environment.

friendlyDate = function( x ){ 

    var label = "Day Month Date Year Time Offset".split(" "),
        d = x ? new Date(x) : new Date(),
        s = ( d + "" ) .split( / / );
        s.length = label.length;
    for( var x in s )s[ label[ x ] ] = s[ x ];
    s.length = 0;

    return s
}
/**/
dte = friendlyDate();
for(var x in dte)console.log(x + ": "+ dte[x]);
p.s.: you might need to readjust\rearrange the labels for certain targeted browsers. [Not all browser vendor\version date string representations are returned equal ;)]
Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26
-1

How to initialize a JavaScript Date to a particular time zone

There is no time zone or string format stored in the Date object itself.

Seems like either string parsing or a library (there are lighter-weight ones than moment if you're interested).

DemiPixel
  • 1,768
  • 11
  • 19