angular $http.post changing date to UTC date - javascript

I was trying to post some data to my REST api which has date.
Now while I debug, my date parameter is a JS Date object with correct date in my timezone: Tue Apr 04 2017 00:00:00 GMT+0530
after it leaves my code, and I see the same in network tab, it is converted to UTC date: "2017-04-03T18:30:00.000Z"
I searched for the solution according to which I need to include locale file of angular in my index.html which I did:
<script type="text/javascript" src="resources/js/angular/angular-locale_en-in.js"></script>
but it doesn't help.
I've seen solutions like adding date format to filter or something, but I want a global solution.
Any help?
Thanks :)

Handling date, time, and timezone have confused me too. May be this answer gives you some insight on how you can handle them.
Try the following code in Chrome's developer console and see how same date is presented in different formats:
var date = new Date();
date.toISOString(); // "2017-04-29T09:54:28.714Z"
date.toGMTString(); //"Sat, 29 Apr 2017 09:54:28 GMT"
date.toLocalString(); //"4/29/2017, 3:24:28 PM"
Any date that you create on client always records the date at zero timezone offset i.e. UTC+/-00:00 Z. For simplicity you may think UTC and GMT as same. When it comes to display purpose the same date is presented as per the browser's timezone. If you do console.log (date) it'll output Sat Apr 29 2017 15:24:28 GMT+0530 (IST) but that doesn't mean that the internal recording of the date is as per browser's timezone. It's just presented on screen/console as per browser's timezone.
Look at date representations not as being converted from one timezone to another but look at them as different representation of the same date. In your browser it is represented as GMT+0530 offset and when it is sent to server it is the same date at zero timezone offset.
As per your comment, if you choose 4th Apr at 00:00 AM in GMT+0530 timezone, internally it'll be 3rd Apr at 18:30 PM in at GMT+0 i.e. zero timezone offset. Let it go to server as it is. When you need to use this date, it comes back from server as 3rd Apr and it'll be displayed in browser as per the browser's timezone offset. There is no conversion involved, it is one date with different representation.
I once asked a related question, may be this adds more clarification.
And overall, this answer is still same as #geminiousgoel and #charlietfl answers.

Scenario :
Send date from UI into API call as an epoch time (UNIX Time) instead of date string. You can use getTime() method to convert the date into epoch time.
var dateStr = "Tue Apr 04 2017 00:00:00 GMT+0530";
var dateEpoch = new Date(dateStr).getTime();
console.log(dateEpoch); // 1491244200000 (Local Time)
At receiver end, they have to convert this epoch time (UNIX time) into Date again.It will give the same local date\time that pass from the UI.
Sample screenshot

Like charlietfl suggested, probably the global hack would be to override Date.prototype.toJSON() method, but that's not a good practice.
Where are you using your $http.post call? The best place to submit an $http request would be in a service. If you use a service, then I suggest you to enwrap your public service API, so that you could have "public" and "private" methods: these could be utilities to perform common operations, such as data transformations, validations..
angular.service('bookStoreService', ['$http'], function($http) {
var normalizeBooks = function(booksArray){
booksArray.forEach(function(book){
// do something on the book
});
};
var updateBooks = function(books){
normalizeBooks(books);
$http.post('myurl', books);
};
return {
updateBooks : updateBooks
};
});

Passing UTC date to server is desired behavior. The client APIs are supposed to handle UTC time instead of assuming the dates are all local dates.
But anyways, you can convert the date to string based on local time zone, and pass the string to server.

i think you just can pass it as string (if the api you use accept strings) with the format you need, let say "Tue Apr 04 2017 00:00:00 GMT+0530" and save it in back-end as string and then when you retrieve it, it will be string and so it will not be changed in any way.

Jindal saab, It will work like this. When we select any date with date picker or just pass any value it takes the original local date but when we pass that value further it converts it into UTC, thereafter it needs to convert to local zone again at receiving end. Database saves date-time in UTC format.

Did you added the angular-locale_en-in.js library to your app? Something like this....
angular.module('myAngularApp', [
'ngLocale'])
Otherwise, the js library won't have any effect in your angular application.

Append UTC at the end so that Browser converts it into UTC date
var dateToServer =new Date(dateFromUser+" UTC");
now the dateToServer will be UTC DateTime format.

Json serializer parse date from string. On a client the date properties are stored as local date in browser time zone. When you are posting your object to server all date properties converts to utc string. In most cases it is a properly behavor. But sometimes you need set and send date in a server time zone. Often it is need when you should set only date whitout time. In that case you should define string propertie and set it manualy. I usaly apply this trick.
class Obj{
d: Date
}
class ObjDto{
constructor(obj: Obj){
this.d= dateTimeToIsoLocalDateString(obj.d)
}
d: string
}
...
export function DateTimeToDate(date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}
export function dateTimeToIsoLocalDateString(dateTime: Date): string {
if (dateTime === null) {
return null;
}
let date = DateTimeToDate(dateTime);
let res = date.toISOString().replace("Z", "");
return res;
}
For more understanding this theme you may learn this topic

//in res data of rest service in x the value is date in y value of y-axis
for (const i in res) {
console.log(i);
const a = {x: new Date(this.mimikatzlog[i].x), y: this.mimikatzlog[i].y};
this.policies.push(a);

Related

Avoid timezone correction for JavaScript Date

I have a JavaScript function that takes a number (1-31), creates a Date and sends it to a server via an AJAX request:
sendDate(d) {
let date = new Date(this.year, this.month, d);
htmx.ajax("GET", "/some/url", { values: { "date": date.toISOString() } });
}
The problem is, that JavaScript is doing some timezone correction which has the effect, that if I create a date like new Date(2022, 09, 14) I get a date Wed Sep 14 2022 00:00:00 GMT+0200 (Central European Summer Time) which when converted to ISO format becomes 2022-09-13T22:00:00.000Z, ie. the previous day.
I know I can use .toLocaleDateString(), but I would like to stick to the ISO-format and I would also like to avoid hacky solutions such as always creating the date with some specified time at the middle of the day or whatever.
Is there a simple way to create a regular date object and pass it on to a server without timezone shenanigans?
Values passed to the Date constructor are treated as local, toISOString uses UTC. Unfortunately ECMAScript doesn't have a timezone–free, date–only form.
If you want to use toISOString to format the timestamp, then one solution is to parse the values as UTC initially, e.g.
sendDate(d) {
let date = new Date(Date.UTC(this.year, this.month, d));
htmx.ajax("GET", "/some/url", { values: { "date": date.toISOString() } });
}
Example:
let d = new Date()
let year = d.getFullYear();
let month = d.getMonth()
let day = d.getDate();
let date = new Date(Date.UTC(year, month, day))
// Always shows the current local date as 00:00:00Z
console.log( date.toISOString() );
You should also trim the Z from the end since the timestamp really is local.
There’s a way to do that: store the date as the UNIX timestamp. I do it this way and when it’s needed, I pass the timestamp from server to client and convert it into local date.
That said, I don’t think it’s a good idea to build the date on client and pass it to the server, since it could be modified on client. I believe it’s mostly done this way (and that’s also how it’s done in my projects): on the server side, you check the current timestamp (at the time request is sent) and do with it whatever you want.
It appears that you allow your user to pick a date. It would be a good approach to convert it then to timestamp and pass it to the server.
How would you do that? If I return date.getTime() and then parse it (in python) with datetime.fromtimestamp(int(request.GET['date']) / 1000) I still get the same timezone issue...
You won't have any issues in this case - apart from the fact your server just could happen to have a different local time. A time-zone independent solution would have to use utcfromtimestamp instead of fromtimestamp.
Either way, the timestamp itself can't have any timezone problems by definition.
See RobG's Answer... using the new Date(Date.UTC(year, month, day)) formatting is much better.

Javascript displaying incorrect date

Im currently testing out running a server with routes etc. and am trying to display the date of the previous person to request that route. Usually when i use the new Date() object i get it in my local time, but for some reason it is displaying it in UTC (coordinated universal time) and im not sure how to change it.
my code is
var date;
var dateArr = [];
var counter = 0;
router.get('/last.txt', function(req, res) {
counter++;
date = new Date().toString();
dateArr.push(date);
if (counter == 1) {
res.send("");
} else {
res.send(dateArr[counter-1]);
}
});
but i keep receiving the date in the format:
Fri Mar 26 2021 07:24:50 GMT+0000 (Coordinated Universal Time)
Any advice would be appreciated!
EDIT: I live in Australia so i think it usually outputs in AEDT
It would appear that UTC is the timezone in place for the server where this code is running. That's fine, you can convert that to the local timezone on the client quite easily. Rather than using toString, though, I would store either the Date object, or its time value (the result of .valueOf()), or the result of .toISOString() and then send either the time value (a number) or the ISO string value to the client. That way, you're not relying on the timezone of the server. When you pass either of those (the time value or the ISO string) into new Date on the client site, the resulting Date will have the same date/time, but because it's operating in the client's timezone, its local time formatting methods like toString, getFullYear, etc., will use the local timezone of the client.
E.g., change toString to (for instance) toISOString in your code, and on the client:
const dt = new Date(theStringFromTheServer);
console.log(dt.toString()); // Will use the client's timezone to show the date/time

Moment.js resolve timezone offset

I'm working in an Angular 6 front end and receive from another system time stamps which have no time zones (C# backend, DateTime). I suspect that javascript is automatically adding the local time zone to Date objects.
Example:
Receiving from backend: 2018-10-15T07:53:00.000Z
When console logging: console.log(timestamp) // Mon Oct 15 2018 09:53:00 GMT+0200
I am using moment.js and already tried moment.utc() and moment(DATE).utc(). But it still adds the local time zone especially because I have to re-transform my moment objects back to the type Date with .toDate().
How can I resolve the time zone difference and get back a utc date to work with or the same structure as received?
try to format use as per desired.
let str = '2018-10-15T07:53:00.000Z';
let moment = moment(str).utcOffset(str)
console.log(moment.format('DD/MM/YYYY HH:mm'))
<script src="https://momentjs.com/downloads/moment.js"></script>
Second Snippet (to use the date object from string)
let str = '2018-10-15T07:53:00.000Z';
let moment = moment(str).utcOffset(str);
console.log(moment.toDate())
<script src="https://momentjs.com/downloads/moment.js"></script>
Your input is UTC and will be parsed just fine. Javascript Dates have no notion of timezone! The local timezone is applied by the static methods for serializing (Date.toString(), Date.toDateString() etc.) (Console.log(Date) uses Date.toString().)
Use Date.toLocaleString([],{timeZone:"UTC"}). Forcing UTC, you will see in the output the same time as the input. Much more details are here :-)
Here it is working:
console.log(new Date('2018-10-15T07:53:00.000Z').toLocaleString([],{timeZone:'UTC'}))

Any way to parse a time string using Moment.js but ignore timezone info?

Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven't had any success.
Is there a way using moment.js to parse an ISO-8601 string but have it parsed in my local timzeone? Essentially I want to ignore the timezone information that is supplied in the ISO string.
For example, if I am in EDT timezone:
var x = moment( "2012-12-31T00:00:00+0000" );
will give me:
"2012-12-30T19:00:00-5000"
I'm looking to ignore the timezone info and just have it give me a moment equivalent of "2012-12-31T00:00:00-5000" local time (EDT).
I don't think you really want to ignore the offset. That would ultimately just be replacing the offset you provided with one from your local time zone - and that would result in a completely different moment in time.
Perhaps you are just looking for a way to have a moment retain the time zone it was given? If so, then use the moment.parseZone function. For example:
var m = moment.parseZone("2012-12-31T00:00:00+0000");
var s = m.format(); // "2012-12-31T00:00:00+00:00"
You could also achieve this with moment.utc. The difference is that moment.parseZone will retain whatever offset you give it, while moment.utc will adjust to UTC if you give it a non-zero offset.
I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.
moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()
This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.
I know I'm late to the party, I had the same question and my searches didn't bring me any closer. I broke down and read the documentation and there is an option in moment for a String + Format:
String + Format docs
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
and more words, then this:
Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
The part that gave me pause was the example that was used to parse local time omitted the +0000, which lead me to think the input string needed to have that removed, but it doesn't.
example:
var time = "2012-12-31T00:00:00+0000";
var x = moment(time); // Sun Dec 30 2012 19:00:00 GMT-0500
var y = moment(time,'YYYY-MM-DD'); //Mon Dec 31 2012 00:00:00 GMT-0500
You can ignore the browser's timezone completely by creating a new moment using moment.utc() instead of moment().
For example, if you are trying to work purely with a UTC date/time of the browser's current time but want to discard its timezone data, you can recreate the browser's current time into a UTC format using the following:
let nowWithTimezone = moment();
let nowInUtc = moment.utc(nowWithTimezone.format('MM/DD/YYYY HH:mm'), 'MM/DD/YYYY HH:mm');
Further documentation on moment.utc(): https://momentjs.com/docs/#/parsing/utc/
If you know for sure your input string is in the ISO-8601 format, you could just strip off the last 5 digits and use that in the Moment constructor.
var input = "2012-12-31T00:00:00+0000"
input = input.substring(0, input.length-5)
moment(input).toString()
> "Mon Dec 31 2012 00:00:00 GMT-0600"
There are valid reasons to do what the OP is asking for. The easiest way to do this with Moment is using its parseZone(date) method. No futzing around with string manipulation or multiple calls. It effectively parses the date string as though it were in the browser's local time zone.
This is difficult task to do with MomentJS, it will basically depend as well on your current timezone.
Documentation as well is vague for this specific task, the way I solved the issue on my side was by adding hours to the date before converting it to JSON format.
var dt = moment("Sun Sep 13 2015 00:00:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400", false);
var date = dt.add(2, 'hour').toJSON();
console.log(date); //2015-09-13T00:00:00.000Z
Momentjs default logic will format the given time with local timezone. To format original date, I wrote a function:
https://github.com/moment/moment/issues/2788#issuecomment-321950638
Use moment.parseZone to convert without taking into account the timezone.
const moment = require('moment')
const dateStr = '2020-07-21T10:00:00-09'
const date = moment.parseZone(dateStr)
console.log(date.format('MM-DD-YY HH:mm A')) // 07-21-20 10:00 AM
Try here link to docs
The best way is to use:
dt = moment("Wed Sep 16 2015 18:31:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400",true);
And to display convert again to desired timezone:
dt.utcOffset("-04:00").toString()
output > Wed Sep 16 2015 18:31:00 GMT-0400

Detect timezone abbreviation using JavaScript

I need a way to detect the timezone of a given date object. I do NOT want the offset, nor do I want the full timezone name. I need to get the timezone abbreviation.
For example, GMT, UTC, PST, MST, CST, EST, etc...
Is this possible? The closest I've gotten is parsing the result of date.toString(), but even that won't give me an abbreviation. It gives me the timezone's long name.
A native solution:
var zone = new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2]
console.log(zone)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
You can pass undefined instead of en-us to default to the browser's current locale.
moment-timezone includes an undocumented method .zoneAbbr() which returns the time zone abbreviation. This also requires a set of rules which are available to select and download as needed.
Doing this:
<script src="moment.js"></script>
<script src="moment-timezone.js"></script>
<script src="moment-timezone-data.js"></script>
<script>
moment().tz("America/Los_Angeles").zoneAbbr();
</script>
Returns:
'PDT' // As of this posting.
Edit (Feb 2018)
Evan Czaplicki has worked on a draft proposal to add a time zone API to browsers.
The Date object doesn't have a method for getting the timezone abbreviation, but it is implicit at the end of the result of toString. For example,
var rightNow = new Date();
alert(rightNow);
...will return something like Wed Mar 30 2011 17:29:16 GMT-0300 (ART). The timezone abbreviation can be isolated between parentheses:
var rightNow = new Date();
alert(String(String(rightNow).split("(")[1]).split(")")[0]);
The output will be the timezone abbreviation, like ART.
This works perfectly in Chrome, Firefox but only mostly in IE11. In IE11, timezones without straight forward abbreviations like "Indian Chagos Time" will return "ICT" instead of the proper "IOT"
var result = "unknown";
try{
// Chrome, Firefox
result = /.*\s(.+)/.exec((new Date()).toLocaleDateString(navigator.language, { timeZoneName:'short' }))[1];
}catch(e){
// IE, some loss in accuracy due to guessing at the abbreviation
// Note: This regex adds a grouping around the open paren as a
// workaround for an IE regex parser bug
result = (new Date()).toTimeString().match(new RegExp("[A-Z](?!.*[\(])","g")).join('');
}
console.log(result);
Result:
"CDT"
You can use the formatToParts method of Intl.DateTimeFormat to get the short time zone abbreviation. In certain parts of the world this may return strings like "GMT+8", rather than the abbreviation of an actual time zone name.
let timeZone = new Intl.DateTimeFormat('en-us', { timeZoneName: 'short' })
.formatToParts(new Date())
.find(part => part.type == "timeZoneName")
.value
console.log(timeZone)
Update for 2021
moment.js is now deprecated and they suggest using Luxon in new projects instead.
You can get a timezone abbreviation with Luxon like:
import { DateTime } from 'luxon'
DateTime.local().toFormat('ZZZZ') // => for ex: "PDT"
Note: The output format depends on the set locale. For more information see this answer.
I was able to achieve this with only moment.
moment.tz(moment.tz.guess()).zoneAbbr() //IST
Using contents from new Date().toString()
const timeZoneAbbreviated = () => {
const { 1: tz } = new Date().toString().match(/\((.+)\)/);
// In Chrome browser, new Date().toString() is
// "Thu Aug 06 2020 16:21:38 GMT+0530 (India Standard Time)"
// In Safari browser, new Date().toString() is
// "Thu Aug 06 2020 16:24:03 GMT+0530 (IST)"
if (tz.includes(" ")) {
return tz
.split(" ")
.map(([first]) => first)
.join("");
} else {
return tz;
}
};
console.log("Time Zone:", timeZoneAbbreviated());
// IST
// PDT
// CEST
You can use the Native Javascript date object.
Just hardcode the long timezone name 'America/Los_Angeles.
var usertimezone = 'America/Los_Angeles';
var usertimezoneabbreviation = new Date().toLocaleTimeString('en-us',{timeZone: usertimezone, timeZoneName:'short'}).split(' ')[2];
console.log(usertimezoneabbreviation); //PDT
If all else fails, you can simply create your own hashtable with the long names and abbreviations.
Updated for 2015:
jsTimezoneDetect can be used together with moment-timezone to get the timezone abbreviation client side:
moment.tz(new Date(), jstz.determine().name()).format('z'); //"UTC"
Moment-timezone cannot do this on it's own as its function which used to handle this was depreciated because it did not work under all circumstances: https://github.com/moment/moment/issues/162 to get the timezone abbreviation client side.
For a crossbrowser support I recommend using YUI 3 Library:
Y.DataType.Date.format(new Date(), {format:"%Z"});
It supports strftime identifiers.
For more information:
http://yuilibrary.com/yui/docs/datatype/#dates
I know the problem remains of differences between browsers, but this is what I used to get in Chrome. However it is still not an abbreviation because Chrome returns the long name.
new Date().toString().replace(/^.*GMT.*\(/, "").replace(/\)$/, "")
Not possible with vanilla JavaScript. Browsers are inconsistent about returning timezone strings. Some return offsets like +0700 while others return PST.
It's not consistent or reliable, which is why you need 3rd party script like moment.js (and moment-timezone.js) or create your own hashtable to convert between offsets and timezone abbreviations.
This is a tricky subject. From what I gather the timezone is not embedded as part of the Date object when it's created. You also cannot set the timezone for a Date object. However, there is a timezone offset you can get from a Date object which is determined by the user's host system (timezone) settings. Think of timezone as a way to determine the offset from UTC.
To make life easier, I highly recommend moment and moment-timezone for handling these things. Moment creates a wrapper object for Date with a nice API for all kinds of things.
If an existing date object is supplied to you through some parameter or something, you can pass it the constructor when creating a the moment object and you're ready to roll. At this point you can use moment-timezone to guess the user's timezone name, and then use moment-timezone formatting to get the abbreviation for the timezone. I would venture to say that most users have their timezone set automatically but you shouldn't rely on this for 100% accuracy. If needed you can also set the timezone you want to use manually before pulling the format you need.
In general when working with date and time it's best to store UTC in your database and then use moment js to format the time for the user's timezone when displaying it. There may be cases where you need to be sure the timezone is correct. For example if you are allowing a user to schedule something for a specific date and time. You would need to make absolutely sure that with a west coast user that you set the timezone to PDT/PST before converting to UTC for storage in your database.
Regarding the timezone abbreviation...
Here is a basic example to get the timezone abbreviation using moment and moment-timezone.
// if all you need is the user's timezone abbreviation you don't even need a date object.
const usersTimezoneName = moment.tz.guess()
const timezoneAbbr = moment().tz(usersTimezoneName).format('z')
console.log(timezoneAbbr) // PST (depending on where the user is)
// to manually set the timezone
const newYorkAbbr = moment(dateObj).tz('America/New_York').format('z')
console.log(newYorkAbbr) // EST
For displaying a specific date object with offsets for a specific timezone you can do this.
const xmas = new Date('December 25, 2017 16:20:00')
const losAngelesXmas = moment(xmas).tz('America/Los_Angeles')
console.log(losAngelesXmas.format("dddd, MMMM Do YYYY, h:mm:ss a")) // Monday, December 25th 2017, 4:20:00 pm
Try this function
function getTimezoneAbbreviation(date) {
// Convert the date into human readable
// An example: Fri Jul 09 2021 13:07:25 GMT+0200 (Central European Summer Time)
// As you can see there is the timezone
date = date.toString();
// We get the timezone matching everything the is inside the brackets/parentheses
var timezone = date.match(/\(.+\)/g)[0];
// We remove the brackets/parentheses
timezone = timezone.replace("(", "").replace(")", "");
// A new variable for the abbreviation
var abbreviation = "";
// We run a forEach dividing the timezone in words with split
timezone.split(" ").forEach((word) => {
// We insert the first letter of every word in the abbreviation variable
abbreviation += word.split("")[0];
});
// And finally we return the abbreviation
return abbreviation;
}
Try Google's Closure Class goog.i18n.DateTimeSymbols and their locale related classes.
Here is a JavaScript self-updating, 12-hour format date/time display that doesn't quite answer the question, however it may help others as it is related and builds on Stephen DuMont's solution and MDN link. W3 Schools had a very helpful tutorial, and real-time updates do not require page refresh.
Tests with the latest versions of desktop FireFox, Chrome, Opera, and Internet Explorer 11 all work. The "2-digits" hour only appears to prefix a zero for single values in IE, however the minutes return a 2-digit value reliably for all browsers. Tests with discontinued Windows Safari work although 12-hour format is ignored and seconds are not hidden.
The function includes the local timezone, as well adjustable options for fall-back languages, day and date display, and 12/24 hour format. Date and time were split to add the separating 'at' string. Setting only 'toLocaleTimeString' with select options will also return both date and time. The MDN pages can be referenced for options and values.
<!--
function dateTimeClock() {
var date = new Date();
document.getElementById('timedate').innerHTML = date.toLocaleDateString(['en-us', 'en-GB'], {
weekday: 'long',
month: 'long',
day: '2-digit',
year: 'numeric'
}) + ' at ' +
date.toLocaleTimeString(['en-us', 'en-GB'], {
hour12: 'true',
hour: '2-digit',
minute: '2-digit',
timeZoneName: 'short'
});
var t = setTimeout(dateTimeClock, 500);
}
function start() {
dateTimeClock();
}
window.onload = start;
//-->
<div id="timedate"></div>
import { tz } from 'moment-timezone';
import * as moment from 'moment';
const guess = tz.guess(true); // "Asia/Calcutta"
const zone = tz.zone(guess); // return Zone object
zone.abbr(new Date().getTime()) // "IST"
// once u pass timestamp it'll return timezone abbrevation.
try {
result = /.*\s(.+)/.exec(date.toLocaleDateString(navigator.language, {timeZoneName:'short' }))[1];
} catch(e) {
result = (new Date()).toTimeString().match(new RegExp("[A-Z](?!.*[\(])","g")).join('');
}
console.log(result);

Categories