Calculating a date and time in another time zone - javascript

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.

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.

how to get timezone offset of different places in 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));

change the time of the start of the day in javascript

Is there a way to set the day to start from 4am not from 12am as we all know, i'm searching for a javascript library or a method to make this available, i'm now using moment.js but I couldn't figure out how to do it.
Thanx for your advice,
Get their local time, and change the timezone to be the timezone of your server plus 4 hours. The timezone of your server is the difference in hours between your local time and GMT.
var GMTdate = new Date();
var timeZoneFromDB = 4.00;
// add or subtract from the timeZone to set it to server time zone plus 4.
// get the timezone offset from local time in minutes
var tzDifference = timeZoneFromDB * 60 + GMTdate.getTimezoneOffset();
//convert the offset to milliseconds, add to targetTime, and make a new Date
var adjustedTime = new Date(GMTdate.getTime() + tzDifference * 60 * 1000);
Javascript date functions using adjustTime will not reflect the date 4 hours later than the date of your server.
Note: the hour will be incorrect of course.
Update ... fixed local time, "their time", to GMT/UTC time.
Updated again ... it was correct the first time. I thought for a moment it needed to start with GMT time (late night due-diligence).
note: if DST is used at server location, change timeZoneFromDb to
var timeZoneFromDB = ((new Date()).dst()) ? '-04:00' : '-05:00';
with correct numbers to adjust to that time zone. Also note DST does not start on the same date universally, to handle it properly the server time zone must be known.

Categories