Handling Time Zone in JavaScript

Convert date to another timezone in JavaScript
https://stackoverflow.com/questions/10087819/convert-date-to-another-timezone-in-javascript

Handling Time Zone in JavaScript
https://medium.com/@toastui/handling-time-zone-in-javascript-547e67aa842d#:~:text=In%20this%20scenario%2C%20you%20can,current%20time%20zone%20in%20minutes.&text=The%20return%20value%20of%20%2D540,minutes%20ahead%20of%20the%20target.

var aestTime = new Date().toLocaleString(“en-US”, {timeZone: “Australia/Brisbane”});
console.log(‘AEST time: ‘+ (new Date(aestTime)).toISOString())

var asiaTime = new Date().toLocaleString(“en-US”, {timeZone: “Asia/Shanghai”});
console.log(‘Asia time: ‘+ (new Date(asiaTime)).toISOString())

var usaTime = new Date().toLocaleString(“en-US”, {timeZone: “America/New_York”});
console.log(‘USA time: ‘+ (new Date(usaTime)).toISOString())

var indiaTime = new Date().toLocaleString(“en-US”, {timeZone: “Asia/Kolkata”});
console.log(‘India time: ‘+ (new Date(indiaTime)).toISOString())
————–
Convert string to datetime
https://stackoverflow.com/questions/5510580/convert-string-to-datetime

Keep it simple with new Date(string). This should do it…

var s = ’01-01-1970 00:03:44’;
var d = new Date(s);
console.log(d); // —> Thu Jan 01 1970 00:03:44 GMT-0500 (Eastern Standard Time)

MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
——————-
Date and Time in JavaScript
https://ayushgp.github.io/date-and-time-in-javascript/

new Date();
// Creates a Date object using the current time and timezone
// Returns:
// Thu Jan 04 2018 12:20:02 GMT+0530 (India Standard Time)

new Date(milliseconds);
// Creates a Date object using the no of milliseconds since epoch
// new Date(0) returns:
// Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)

new Date(dateString);
// Creates a date object using a date format which is accepted by the Date.parse method.
// You can read more about the supported date string formats here:
// http://tools.ietf.org/html/rfc2822#page-14

// new Date(“1970-01-01”) returns:
// Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)

new Date(year, month, day, hours, minutes, seconds, milliseconds);
// This representation is the easiest to comprehend as it accepts the date
// in form of 7 arguments. All the values should be in Integer format

// Note: The month argument is from 0 to 11 and not from 1 to 12

—————————
Converting UTC date time from server to local date time on the browser client using JavaScript
http://sundeepkamath.in/posts/javascript-converting-utc-date-time-from-server-to-local-date-time-on-the-browser-client/

———————
Convert the local time to another time zone with this JavaScript

Convert the local time to another time zone with this JavaScript

Note: In case you’re wondering how I arrived at 60000 as the multiplication factor, remember that 1000 milliseconds = 1 second, and 1 minute = 60 seconds. Therefore, converting minutes to milliseconds involves multiplying by 60 * 1000 = 60000.

Note: In case you’re wondering how I arrived at 3600000 as the multiplication factor, remember that 1000 millseconds = 1 second, and 1 hour = 3600 seconds. Therefore, converting hours to milliseconds involves multiplying by 3600 * 1000 = 3600000.

// function to calculate local time
// in a different city
// given the city’s UTC offset
function calcTime(city, offset) {

// create Date object for current location
d = new Date();

// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);

// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));

// return time as a string
return “The local time in ” + city + ” is ” + nd.toLocaleString();

}

// get Bombay time
alert(calcTime(‘Bombay’, ‘+5.5’));
——————
Autodetect and prompt when device timezone is changed in angular7
https://stackoverflow.com/questions/54871236/autodetect-and-prompt-when-device-timezone-is-changed-in-angular7

JavaScript doesn’t have a built-in method for this, but you can use a library. For example, Moment-timezone provides the moment.tz.names() function, and Date-fns-timezone provides the listTimeZones() function.

.. some timezone returns “Asia/Kolkata” and “Asia/Calcutta”

——————
Updating time offset with moment().utcOffset()
https://stackoverflow.com/questions/32878197/updating-time-offset-with-moment-utcoffset
moment.utc(“2015-10-01 01:24:21”).utcOffset(-240).format(‘YYYYMMDD HHmmss ZZ’)
// “20150930 212421 -0400”
————
Convert moment utcOffset to Datefns or native Javascript
https://stackoverflow.com/questions/57839186/convert-moment-utcoffset-to-datefns-or-native-javascript

——————–
Get or estimate browsers timezone name in JavaScript
https://gist.github.com/eikes/1836260

var d = new Date();
var usertime = d.toLocaleString();

// Some browsers / OSs provide the timezone name in their local string:
var tzsregex = /\b(ACDT|ACST|ACT|ADT|AEDT|AEST|AFT|AKDT|AKST|AMST|AMT|ART|AST|AWDT|AWST|AZOST|AZT|BDT|BIOT|BIT|BOT|BRT|BST|BTT|CAT|CCT|CDT|CEDT|CEST|CET|CHADT|CHAST|CIST|CKT|CLST|CLT|COST|COT|CST|CT|CVT|CXT|CHST|DFT|EAST|EAT|ECT|EDT|EEDT|EEST|EET|EST|FJT|FKST|FKT|GALT|GET|GFT|GILT|GIT|GMT|GST|GYT|HADT|HAEC|HAST|HKT|HMT|HST|ICT|IDT|IRKT|IRST|IST|JST|KRAT|KST|LHST|LINT|MART|MAGT|MDT|MET|MEST|MIT|MSD|MSK|MST|MUT|MYT|NDT|NFT|NPT|NST|NT|NZDT|NZST|OMST|PDT|PETT|PHOT|PKT|PST|RET|SAMT|SAST|SBT|SCT|SGT|SLT|SST|TAHT|THA|UYST|UYT|VET|VLAT|WAT|WEDT|WEST|WET|WST|YAKT|YEKT)\b/gi;

// In other browsers the timezone needs to be estimated based on the offset:
var timezonenames = {“UTC+0″:”GMT”,”UTC+1″:”CET”,”UTC+2″:”EET”,”UTC+3″:”EEDT”,”UTC+3.5″:”IRST”,”UTC+4″:”MSD”,”UTC+4.5″:”AFT”,”UTC+5″:”PKT”,”UTC+5.5″:”IST”,”UTC+6″:”BST”,”UTC+6.5″:”MST”,”UTC+7″:”THA”,”UTC+8″:”AWST”,”UTC+9″:”AWDT”,”UTC+9.5″:”ACST”,”UTC+10″:”AEST”,”UTC+10.5″:”ACDT”,”UTC+11″:”AEDT”,”UTC+11.5″:”NFT”,”UTC+12″:”NZST”,”UTC-1″:”AZOST”,”UTC-2″:”GST”,”UTC-3″:”BRT”,”UTC-3.5″:”NST”,”UTC-4″:”CLT”,”UTC-4.5″:”VET”,”UTC-5″:”EST”,”UTC-6″:”CST”,”UTC-7″:”MST”,”UTC-8″:”PST”,”UTC-9″:”AKST”,”UTC-9.5″:”MIT”,”UTC-10″:”HST”,”UTC-11″:”SST”,”UTC-12″:”BIT”};

var timezone = usertime.match(tzsregex);
if (timezone) {
timezone = timezone[timezone.length-1];
} else {
var offset = -1*d.getTimezoneOffset()/60;
offset = “UTC” + (offset >= 0 ? “+” + offset : offset);
timezone = timezonenames[offset];
}

document.write(usertime + “
“);
document.write(offset + “
“);
document.write(timezone + “
“);
————-
Compensate for utcOffset in Moment.js
https://stackoverflow.com/questions/36968212/compensate-for-utcoffset-in-moment-js
What you are seeing here is the fact that the JS Date object and MomentJS both contain, internally, a Unix Time stamp in milliseconds. These time stamps are a reference to a point on the global timeline that can be converted to local time if desired.

When you use the default moment() constructor, you are telling Moment to operate in ‘local’ mode. What this means is that when Moment displays the date that it contains, it will convert from the UTC Unix time stamp that it contains internally, to the local time of the user.

If you wanted to keep the UTC time (which you don’t) you could pass the JS Date object that you are getting from your date picker to the moment.utc() function, and then when you called .format() on that moment, you would always see the UTC time.

As an example, I am on United States Central Daylight Time right now, making my offset -5.

If I take your example UTC time stamp and pass it to the default moment constructor, I get the following:

moment(‘2016-05-19T23:00:00.000Z’).format()
“2016-05-19T18:00:00-05:00”

As you can see, for display purposes, Moment has converted to my local time zone.

If I were to use UTC though:
moment.utc(‘2016-05-19T23:00:00.000Z’).format()
“2016-05-19T23:00:00+00:00”

No change.

You do not need to worry about the clock change that you are talking about in your comment. Since your date picker is giving you an exact point on the global timeline, moment will always be able to correctly convert to local.

As to why .toISOString() always gives you a UTC date when you call it on a JS Date object – you can thank the TC39 committee for that one. That is how it is supposed to work per the ES2015 spec: http://www.ecma-international.org/ecma-262/6.0/#sec-date.prototype.toisostring

Moment also always provides UTC for .toISOString() for the sake of consistency with the way native date works.
——
How can I convert string to datetime with format specification in JavaScript?
https://stackoverflow.com/questions/476105/how-can-i-convert-string-to-datetime-with-format-specification-in-javascript
———-
How to get timezone name (PDT, EST, etc.) in Javascript?
https://stackoverflow.com/questions/40494995/how-to-get-timezone-name-pdt-est-etc-in-javascript

Using moment.js with the moment-timezone add-on, you can do the following. The results will be consistent regardless of browser or operating system, because the abbreviations are in the data provided by the library.

The example results are from a computer set to the US Pacific time zone:

var zone = moment.tz.guess(); // “America/Los_Angeles”
var abbr = moment.tz(zone).format(“z”); // either “PST” or “PDT”, depending on when run

DISCLAIMER

Time zone abbreviations are not reliable or consistent. There are many different lists of them, and there are many ambiguities, such as “CST” being for Central Standard Time, Cuba Standard Time and China Standard Time. In general, you should avoid using them, and you should never parse them.


moment utc, does date-fns have something similar?
https://stackoverflow.com/questions/52833680/moment-utc-does-date-fns-have-something-similar

Objects provided by the Moment.js library have the concept of “modes”. A moment object can be in local mode, utc mode, or be fixed to a particular time zone offset. It can also belong to a named time zone via the moment-timezone add-on library. When you call moment.utc(), you are setting the moment object to UTC mode.

Date-fns is an excellent library that provides helper functions that work with the Date standard object provided by the JavaScript language (in the ECMAScript standard). Thus, its functions are limited to what you can do with a Date object.

The Date object does not have modes in the way that moment does. Thus, you cannot switch a Date object to UTC mode using Date-fns or any other vanilla js technique.

The Date object always tracks a UTC point in time internally, and it exposes some functions and parameters that take UTC time, and others that take local time. Any that use local time are converting/to from UTC at the time of the function call. In other words, if you call new Date(year, month, day, hour, minute, second), those values are in local time, and they are converted immediately to UTC. You can get the internal value at any time by calling .getTime() or .valueOf(). If you want a more common representation, .toISOString() is a great option.

In conclusion: You can’t convert a Date object to UTC because it is already in UTC. You can only ask for UTC or local time output, based on the functions you call.
————
Time zone issue involving date fns format()
https://stackoverflow.com/questions/48172772/time-zone-issue-involving-date-fns-format

You will need to subtract the time zone offset of your local time zone from the Date instance, before you pass it to format from date-fns. For example:

const dt = new Date(‘2017-12-12’);
const dtDateOnly = new Date(dt.valueOf() + dt.getTimezoneOffset() * 60 * 1000);
console.log(format(dtDateOnly, ‘YYYY-MM-DD’)); // Always “2017-12-12”

Problem
You want to handle only the date part of the Date instance, because the time part does not make sense for birthdates. However, the Date object does not offer any “date-only” mode. You can access both its date and time parts in the local time zone or UTC. The problem is, that format from date-fns prints the output always in the local time zone.

When you executed the constructor only with the date part:

const dt = new Date(‘2017-12-12’);
The JavaScript engine actually assumed a string in the incomplete ISO 8601 format and perfomed this:

const dt = new Date(‘2017-12-12T00:00:00.000Z’);
It may still look “harmless” to you, but the date instance exposes the value not only in UTC, but also in the local time zone. If you construct the Date instance on the East Coast of the US, you will see the following output:

> const dt = new Date(‘2017-12-12’);
> dt.toISOString()
‘2017-12-12T00:00:00.000Z’
> dt.toString()
‘Tue Dec 11 2017 19:00:00 GMT-0500 (EST)’
> d.toLocaleString()
’12/11/2017 7:00:00 PM’
Solution
Alternative
———–

JavaScript: Display the current day and time in a specific format AM : PM
https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-1.php

Why you shouldn’t use Moment.js…
https://inventi.studio/en/blog/why-you-shouldnt-use-moment-js
Learn date-fns: A Lightweight JavaScript Date Library
https://www.sitepoint.com/date-fns-javascript-date-library/
—————–
date-fns | How do I format to UTC
https://stackoverflow.com/questions/58561169/date-fns-how-do-i-format-to-utc

I would suggest using the built-in Date util:

const date = new Date(“2019-10-25T08:10:00Z”);
const isoDate = date.toISOString();

console.log(`${isoDate.substr(0, 10)} ${isoDate.substr(11, 8)}`);
Outputs:

2019-10-25 08:10:00

Not a general solution for any format, but no external libraries required.
——-

Time Utils

currentDate / Time in Millisecondsmillis
https://currentmillis.com/

UTC to IST to CST
https://savvytime.com/converter/utc-to-ist-cst/sep-24-2020/8am

Time Zone Converter
https://timezoneconverterapp.com/

Leave a Reply

Your email address will not be published. Required fields are marked *