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);
Related
I have future date and now date. Both of this dates are always in same day but with just different hours. My goal is to get the difference of seconds between the future date and now date as my countdown value for a timer. The problem is when I calculate I'm getting inaccurate results.
In my research formula of converting milliseconds to seconds is millis / 1000.0 but non of this returns accurate countdown result;
My code
let now = (new Date().getTime() / 1000.0);
let futureDate = (new Date('2022-04-01T17:41:47.000Z').getTime() / 1000.0);
let difference;
difference = (futureDate - now); // not accurate
difference = parseInt(difference, 10); // not accurate
I would like the solution to work normal on all timezones and to inherit local system timezone instead of future date timezone.
Any help will be appreciated so much.
You should add the system timezone, like this:
let date = new Date('2022-04-01T17:41:47.000Z');
let now = new Date().getTime() / 1000.0;
let futureDate = (date.getTime() + date.getTimezoneOffset() * 60000) / 1000.0;
let difference;
difference = (futureDate - now); // not accurate
difference = parseInt(difference, 10); // not accurate
console.log(difference);
I want to check if you know that date formats like "0000-00-00T00:00:00.000Z" are always recognized as universal time (UK time).
Try using +HH:MM instead of the last Z character.
For example, if you are in the US East, it would be "2022-04-01T17:41:47.000-05:00".
The timestamp '2022-04-01T17:41:47.000Z' will be parsed as offset +0 (aka UTC or GMT) due to the trailing "Z", denoting a +0 offset. The difference between now and then in milliseconds is:
let diff = new Date('2022-04-01T17:41:47.000Z') - Date.now();
where a negative value for diff means the timestamp is in the past. To convert the difference to seconds, divide the result by 1,000.
If run at exactly the same time, the value for diff will be the same regardless of system settings for local offset (allowing for clock accuracy of course).
For the timestamp to be parsed as local, remove the Z:
let diff = new Date('2022-04-01T17:41:47.000') - Date.now();
However, that shifts the instant in time represented by the timestamp by the local offset, so will return a different value for diff for each system with a different offset. That doesn't seem like a sensible thing to do given the timestamp has an offset and so is intended to represent a single instant in time, not one of many different instants (as many as there are different offsets, perhaps hundreds if historical offsets are included) depending on the host offset.
I'm trying to use moment.js to compare a date stored in the database (which is set to Europe/London timezone) against the current users time, taking into account their timezone.
I get a date string returned from the database and want to use the fromNow() function, as follows:
console.log(dbDate);
console.log(moment().format());
console.log(moment(dbDate).fromNow());
// DB stored time (Europe/London)
// 2017-09-26 06:56:26
// Current user time (timezone is Pacific Time / Los Angeles)
// 2017-09-25T23:59:03-07:00
// String output by fromNow() function, which should reflect the timezone difference but doesn't
// in 7 hours
I want the fromNow() string to take account the timezone difference and this should always be a time "ago" as opposed to in the future.
I'm probably missing something quite obvious with the library, so apologies in advance if this is very simple.
// get the current time so we know which offset to take
var now = moment.utc();
// get the zone offsets for this time, in minutes
var NewYork_tz_offset = moment.tz.zone("America/New_York").offset(now);
var MY_DATE = moment(dbDate);
// calculate the difference in hours
console.log((NewYork_tz_offset - MY_DATE) / 60);
Does this help your cause?
You have to use moment timezone, you can parse dbDate specifying "Europe/London" timezone using moment.tz:
The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
Then you can use moment diff and fromNow.
Here a live example:
var dbDate = "2017-09-26 06:56:26";
var now = moment();
var momDbDate = moment.tz(dbDate, "Europe/London");
var pacificTime = moment("2017-09-25T23:59:03-07:00");
console.log(dbDate);
console.log(moment().format());
console.log(momDbDate.fromNow());
console.log(momDbDate.diff(now, 'hours'));
console.log(momDbDate.diff(pacificTime, 'hours'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>
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.
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.