how to get timezone offset of different places in javascript - javascript

I need to get the current time of different places using javascript.
I would get the UTC using following method.
function calcUTC() {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() - (d.getTimezoneOffset() * 60000);
return utc;
}
Now I need to find the timezoneOffset of a particular place so that i can add this offset to the utc to get the current time of the location.
The places could be US,CANADA or any other. there are three different timezones in US. kindly do the possible
Thanks

getTime() method of Date object itself returns UTC value.
Refer: MDN Date object getTime Method
It says,
Method returns the numeric value corresponding to the time for the
specified date according to universal time.
You should not need to subtract or add local time zone offset.
In order to calculate local time for other time zones, you would need to find the offset values for these time-zones (this should take into account the daylight saving time).
Note: JavaScript Date object does not provide any method that takes time zone as input and returns offset for that timezone.
Also, if offset value is absolute, you will need to subtract or add offset, depending upon whether the time zone is before or after GMT.

If you know the time zone offset of the place you want the time of, it's quite simple to just use UTC methods. For example:
/*
** #param {number} offsetInMinutes - Timezone offset for place to be returned
** +ve for east, -ve for west
*/
function timeAt(offsetInMinutes) {
function z(n){return (n<10? '0':'') + n}
var now = new Date();
now.setUTCMinutes(now.getUTCMinutes() + offsetInMinutes);
return z(now.getUTCHours()) + ':' + z(now.getUTCMinutes()) + ':' + z(now.getUTCSeconds());
}
So for a place UTC+0200 you'd do:
console.log(timeAt(120));
and for a place UTC-0430 you'd do:
console.log(timeAt(-270));

Related

Is there a way to get date in another timezone in milliseconds like Date.now() in JavaScript?

new Date(Date.now()).toLocaleString(
"en-US",
{
timeZone: "Asia/Calcutta"
}
)
Works for my timezone. But when I try to get for another timezone, it doesn't help. I tried using Date.parse() and moment, no luck. Would be helpful if there is some other way. I am trying to work on time setting feature for different timezones. Hence I need a function to return current time in that timezone.
Time returned by Date.now() will be the same for any time zone, because it returns how many ms have passed since 01-01-1970
What you need is to calculate GMT offset for your desired time zone
var offset = new Date().getTimezoneOffset();
console.log(offset);
The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale
ECMAScript Dates are simply a time value that is an offset from 1970-01-01T00:00:00Z (the ECMAScript epoch, which is the same as the Java and UNIX epoch).
If a system's clock is accurately set to the current time, then Date.now() and new Date().getTime() for a particular instant will return exactly the same value regardless of the timezone offset of the host system. In practice there will however be minor variations due to clock inaccuracies and lack of syncrhonisation.
The host timezone offset comes from the host system and is only used for calculations involving local values, it's not an attribute of the Date itself.
If you want to get the time value for a particular date and time for a particular timezone offset, you can build a string that should be parsable by the built–in parser and use that. E.g. the Line Islands have an offset of +14:00 and don't observe daylight saving, so to get the time value for Christmas morning use a supported string format1 and the built–in parser:
// Christmas morning in Line Islands
let s = '2019-12-25T00:00:00+14:00';
// Get time value
let ms = Date.parse(s);
let d = new Date(ms);
let optsLocal = {weekday:'short', day:'numeric', month:'short', year:'numeric', hour:'numeric', hour12:false, minute:'numeric'};
let optsHK = Object.assign({},optsLocal,{timeZone:'Asia/Hong_Kong'});
let optsNY = Object.assign({},optsLocal,{timeZone:'America/New_York'});
let optsHW = Object.assign({},optsLocal,{timeZone:'Pacific/Honolulu'});
console.log('Start string: ' + s +
'\nTime value : ' + ms +
'\nLocal date : ' + d.toLocaleString('en-GB', optsLocal) +
'\nHong Kong : ' + d.toLocaleString('en-GB', optsHK) +
'\nNew York USA: ' + d.toLocaleString('en-GB', optsNY) +
'\nHawaii USA : ' + d.toLocaleString('en-GB', optsHW)
);
Where "supported string format" is one of the two formats specified in ECMA-262, also see Why does Date.parse give incorrect results?

Get current timestamp from a specific timezone in javascript

I'm trying to get a timestamp from a specific timezone that is independent of the local time.
I want my clients from all over the world to see the exact same timestamp. Is this even possible? I don't want a solution in node.js but if there is a working library, please include it.
You can either generate a timezone independent timestamp by means of JavaScript, using Date object, or using specialized libraries such as moment.js:
const timestampMilliseconds = (new Date()).getTime();
console.log(timestampMilliseconds);
const timestampSeconds = Math.round((new Date()).getTime() / 1000);
console.log(timestampSeconds);
const timestampSecondsMoment = moment().unix();
console.log(timestampSecondsMoment)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
You say that you want to get a timestamp for a "specific time zone". If you know what the time zone offset is for that specific time zone then you should be able to get a UTC date, subtract the time zone offset from it and output a date string that should be the same on all clients. This statement should work:
var timeZoneOffset = 300; // Eastern Standard Time
var sameDate = (new Date(((new Date()) - (timeZoneOffset * 60 * 1000)))).toISOString()
new Date() should return the same time in milliseconds on all clients if the date and time of the local machines are accurate. Time zone offsets are in minutes so you need to multiply them be 60 * 1000 (60 seconds/minute times 1000 milliseconds/second) and then subtract that many milliseconds from the UTC date to get it to equal the current time in the time zone that has that offset. Then convert it to an ISO string. You can manipulate the resulting string if you want. Perhaps get rid of the Z on the end.
var dateWithoutZ = sameDate.slice(0,-1);

format datetime specific timezone

I am using globalize to format datetime per locale.
var Globalize = require('globalize');
var formatter = Globalize('en-US').dateFormatter();
formatter(new Date());
It works great but I was wondering if I can format date for specific timezone. This way, it always formats date in the local machine timezone.
For example, let's say my machine timezone is PST. Can I use globalize to format date in EST?
Stolen from here
This solution works by using the getTimeOffset() (which returns the time difference between UTC time and local time, in minutes) function to find the UTC time offset of a given location and changing it to milliseconds, then performing calculations from UTC to return a time for a different time zone.
/**
* 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
var d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
This solution will work, but it's simpler to express timezone in minutes and adjust the UTC minutes.
Please let me know if this works for you!
The javascript function new date() generates a date/time stamp based off the machine time at the moment that the function was called. So if the function is called by a machine that is in Alaska, it will generate a date/time stamp based on the current time in Alaska at that exact moment.
w3school.com has great references to most coding related items. You can find the answer to your question here.

Calculating a date and time in another time zone

This has been driving me around the twist for several days now.
The application is in JavaScript.
I'm wish to show the time in one time zone for a viewer in another time zone.
I would store the time zone offset from GMT (Daylight saving would be taken in to account with the offset) for the zone I want to display the time and date for.
I was planning on converting the time to Epoch and then adding or subtracting the offset and then convert to DD MM YYYY HH MM SS for the date calculated.
I've got to the point that I can no longer see the wood for the trees. Any thoughts on how to achieve this.
Since Dates are based on a UTC time value, you can just adjust for the offset you want and read UTC values, e.g.
/* #param {number} offset - minutes to subtract from UTC to get time in timezone
**
*/
function getTimeForOffset(offset) {
function z(n){return (n<10?'0':'')+n}
var now = new Date();
now.setUTCMinutes(now.getUTCMinutes() - offset);
return z(now.getUTCHours()) + ':' + z(now.getUTCMinutes()) + ':' + z(now.getUTCSeconds());
}
// Time for AEST (UTC+10)
console.log(getTimeForOffset(-600));
// Time for CEST (UTC+02)
console.log(getTimeForOffset(-120));
Note that the offset has the same sign as the javascript Date timezone offset, which is opposite to the typical value that is added to UTC to get the local time.

Convert date in one timezone to another timezone using timezone abbreviations

I am working on a web application where a user can set his/her timezone in the application which is further used in the application for various date-time conversions. The selected timezone can be different from user's locale timezone.
I am currently stuck on a problem where I need to compare a user selected date(which user assumes to be in the timezone selected by him/her in the application) with the current date to see if the selected date is a date in future. With reference to all the places I have searched, I have found that I can get current date in user locale or UTC time.
So the gist of my problem is - Is there any way to convert a date from one timezone to another using the timezone abbreviations?
I have searched a lot before posting here but could not get any solution. Most of the places that I found during my search suggest that there is no such solution available.
I have tried using date.js but it does not suffice the purpose as it is quite outdated and also the timezone abbreviations supported by it is a very limited set. I have also taken a look a timezoneJS but I don't think that it works with timezone abbreviations.
Is there any way in which it can be accomplished using javascript or jquery?
Here you go:
// calculate local time in a different city given the city's UTC offset
function calcTime(city, offset) {
// create Date object for current location
var date = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var newDate = new Date(utc + (3600000 * offset));
// return time as a string
return "The local time in " + city + " is " + newDate.toLocaleString();
}
// get Bombay time
console.log(calcTime('Bombay', '+5.5'));
// get Singapore time
console.log(calcTime('Singapore', '+8'));
// get London time
console.log(calcTime('London', '+1'));

Categories