I have a unix timestamp like:
1647386880
I want to apply -0400 offset to this value, is this possible in javascript w/o any external libraries?
No library needed. If you know a datetime in the unix timestamp format and you just want to adjust it by 4 hours, you can add/subtract as needed.
(presuming the datestamp is in GMT, and you are not worried about DST (without an actual timezone location any DST can't be determined)
-0400 would be minus 4 hours, thus 4x60x60= 14,400.
let origDatestamp = 1647386880;
let offsetDatestamp = origDatestamp - 14400;
If your offsets will vary, but always be in the standard format you supplied "[-]HHMM", you could create a function to simplify this.
function applyOffset(gmtTimestamp, offset){
return gmtTimestamp + (parseInt(offset) / 100) * 60 * 60;
}
Note there was another answer posted that seems to have been removed (it had potential too!) - just note that offsets are typically to the hour, but there are some that are not e.g. https://www.timeanddate.com/time/time-zones-interesting.html e.g. Newfoundland Canada at -0230
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.
Given the current UTC time and a specific hour of the day, I want to find the timezone offset in minutes. The function below works (I think) for all timezones when the hour is midnight (excluding the few timezones that start at 30 and 45 minutes, but those are still covered by the timezone range if this runs every hour).
function getCurrentGlobalTimeOffset(currentGlobalTime) {
var currentGlobalHour = dateFormat(currentGlobalTime, 'H');
if (currentGlobalHour <= 11) {
var currentGlobalOffsetStart = currentGlobalHour * 60;
var currentGlobalOffsetEnd = (currentGlobalHour * 60) + 60;
} else {
var currentGlobalOffsetStart = (24 - currentGlobalHour) * -60;
var currentGlobalOffsetEnd = ((24 - currentGlobalHour) * -60) + 60;
}
return {
start: currentGlobalOffsetStart,
end: currentGlobalOffsetEnd
}
}
I'm struggling to figure out how to incorporate a specific hour. For example, if I want to get the timezone offset for when it is 9:00 AM Pacific time, the expected result at 2019-02-23T17:00:00.000Z UTC time would be:
{
start: 480,
end: 540
}
I've also tried finding a library that does this but I haven't had any luck. As far as I can tell moment.js doesn't offer this capability.
What's the best way to accomplish this?
It's not possible to accomplish what you are asking with 100% confidence in the results, which is why you won't find a function for this in Moment.js or other libraries. The reason is that time zone offsets of the world are presently in the range of UTC-12 to UTC+14, thus there is an overlap where such a function would have ambiguous results.
Consider as an example 2019-02-23T20:00:00Z (UTC). That is both 2019-02-23T09:00:00-11:00 (in American Samoa) and 2019-02-24T09:00:00+13:00 (in New Zealand) (reference here). So if the current UTC hour is 20 and the given local hour is 9, should this function return -11 or +13?
The best one could do would be to calculate both potential offsets, then see if one of them is out of range to exclude it. Or, one could narrow the range such that it didn't overlap, if one didn't care about working with data for the entire world.
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);
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));
For example I have this:
d = new Date(2013,04,20,14,56,10)
Mon May 20 2013 14:56:10 GMT+0800 (SGT)
dt = d.getTime() /1000
1369032970
Now, timezoneOffset value is
d.getTimezoneOffset()*60
-28800
So if I reduce it, I get
dt -= d.getTimezoneOffset()*60
1369061770
My question is, is 1369032970 my local timestamp, and 1369061770 UTC timestamp?
Can I safely say that any current timestamp reduced by the timezoneOffset is the UTC timestamp?
The result from getTime is in milliseconds since 1/1/1970 UTC. The local time zone plays no part in it. So if your question was how to get the UTC timestamp, simply use the result from getTime without any modification.
The idea of a "local timestamp" isn't very useful. One might apply an offset to the UTC timestamp before rendering it to a human-readable date string - but in Javascript, that's already done for you behind the scenes. You really don't want to pass a numeric timestamp to anyone else unless it is strictly UTC, because the meaning of what is "local" would be lost.
Also, when you call getTimezoneOffset, you are getting back the specific offset at the moment represented by the date - in minutes. Also, the sign is the opposite of what we normally see for time zone offsets. For example, I live in Arizona where the offset is UTC-07:00 year-round. But a call to getTimezoneOffset returns a positive value of 420. If you were to apply it a timestamp, you would do the following:
dt -= dt.getTimezoneOffset() * 60 * 1000;
You almost had it, but forgot to convert from seconds to milliseconds. But like I said, this value is meaningless. If you created a new Date object from it, it would display with the offset applied twice - once by your own code, and again by the Javascript internals.