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.
Related
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);
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.
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));
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.
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'));