Calculating JavaScript date time with offset - javascript

I am experiencing some unexpected results with a GMT time zone offset calcultaion.
I am using the ExtJS date class to help calculate the time that a message arrives from the server at GMT 0 to the user's local machine which is currently GMT +8.
I thought that if i calculated the offset, then added that to the timestamp in seconds then i could use the following calculation to give me a string to format as i please.
var d = new Date((stamp + offset) * 1000);
stamp is the date/time in seconds as is the offset.
This returns the current date and time at my location but plus 8 hours. If i do not add the offset then the time is correct.
Does the method new Date() automatically give me the date/time at local time?

Just adding this in case it helps others looking latter. May be wrong but works for what I needed.
I have the user's offset stored in seconds.
offset assumed in seconds change the (offset * 1000) to make sure offset gets converted to milliseconds if your offset not in seconds.
function offsetDate(offset){
var d = new Date(new Date().getTime() + (offset * 1000));
var hrs = d.getUTCHours();
var mins = d.getUTCMinutes();
var secs = d.getUTCSeconds();
//simple output
document.write(hrs + ":" + mins + ":" + secs);

just insert a unix timestamp containing the thousandth of a second.
that unix timestamp should be UTC 0 and javascript will look up the local timezone of the clients computer and will calculate it.
as you can see behind this link, there are some UTC methods wich give you the time without local time offset. maybe this might be what you search for (in case you really want to set the timezone yourself).
edit:
new Date().getTimezoneOffset() will show you the difference between the local timezone and utc but you should consider using the utc methods.

From the looks of it, stamp is your local time including timezone offset. JavaScript has no knowledge of the timezone of the server, it's (mainly) a client-side language.

Related

Is there any possible way to find the timezone using the ISOtime format in javascript

localDate: "2020-10-13"
localTime: "20:00:00"
dateTime: "2020-10-14T01:00:00Z"
I have these three datas, how to find the timezone using these data.
Assuming your inputs are exactly as given:
var localDate = "2020-10-13";
var localTime = "20:00:00";
var dateTime = "2020-10-14T01:00:00Z";
var offsetMillis = new Date(localDate + 'T' + localTime + 'Z') - new Date(dateTime);
var offsetHours = offsetMillis / 36e5;
console.log(offsetHours); // -5
The result is -5, which is 5 hours behind UTC. This works by creating two date objects, one that is UTC-based, and one that pretends to be UTC-based but is actually using the local values. Subtracting the two yields the offset.
Keep in mind - this is an offset from UTC, not a time zone. One cannot determine the time zone from the offset alone. See "Time Zone != Offset" in the timezone tag wiki for more details.
Also keep in mind that not all time zone offsets will be in whole hours. For example, India uses UTC-5:30, so expect -5.5 from this code in such a case. (There also exist time zones with 45-minute offsets.)

javascript returning accurate date when time is 23:59:59.000

I'm returning a date from json and parsing it to a date format like so;
var date = new Date(parseInt(date.substr(6)));
The problem is the date field in the database is set to 23:59:59.000 for the time.
The above code returns the day after using date.getDate().
I'm assuming this is due to the time.
How can i return the accurate date with the time being set to 23:59:59.000
Cheers
Edit
Incase anyone comes across this i fixed it by using;
var utc = new Date(date.getTime() + date.getTimezoneOffset() * 60000);
Assuming that the database is storing the UNIX Epoch (in secs), try multiplying the parseInt with * 1000. This will also set the miliseconds to 0.
let timeFromDB = parseInt(date.substr(6)) * 1000
let date = new Date(timeFromDB);
Date API
Integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix timestamp functions count in seconds).
The question was somewhat unclear, but hope this helps.

How to get hours and minutes in desired timezone without creating new moment object?

I have to display a string on the web page in this format: 16:00 HH:mm
I'm using a moment object to represent a date/time and timezone.
var day = moment().tz('GMT');
day.hours(16).minutes(0).seconds(0).milliseconds(0);
So this is 16:00 in GMT time.
On my web page I want to change the time zone and then collect the hours and minutes.
If I make a new moment object
var day2 = moment().tz('PST); //this is 8 AM since gmt was 16
console.log(day2.get('hours'));
it is 16 not 8!
and try to get the hours and minutes they are in GMT not in PST.
How can I get it in PST? Do I have to keep wrapping it?
// initialize a new moment object to midnight UTC of the current UTC day
var m1 = moment.utc().startOf('day');
// set the time you desire, in UTC
m1.hours(16).minutes(0);
// clone the existing moment object to create a new one
var m2 = moment(m1); // OR var m2 = m1.clone(); (both do the same thing)
// set the time zone of the new object
m2.tz('America/Los_Angeles');
// format the output for display
console.log(m2.format('HH:mm'));
Working jsFiddle here.
If you can't get it to work, then you haven't correctly loaded moment, moment-timezone, and the required time zone data. For the data, you either need to call moment.tz.add with the zone data for the zones you care about, or you need to use one of the moment-timezone-with-data files available on the site.
In the fiddle, you can see the moment-files I'm loading by expanding the External Resources section.
PST can mean different things in different regions. In the moment-timezone docs, I see nothing referring to "PST" or similar abbreviations.
Perhaps try:
var day2 = moment().tz('PST');
// 16 with Error: Moment Timezone has no data for PST. See http://momentjs.com/timezone/docs/#/data-loading/.
var day2 = moment().tz('America/Los_Angeles');
// 15
I don't know about using moment.js, but it's fairly simple using POJS and the same algorithm should work. Just subtract 8 hours from the UTC time of a date object and return a formatted string based on the adjusted UTC time.
Assuming PST is "Pacific Standard Time", also known as "Pacific Time" (PT), and is UTC -8:00:
/* #param {Date} date - input date object
** #returns {string} - time as hh:mm:ss
**
** Subtract 8 hours from date UTC time and return a formatted times string
*/
function getPSTTime(date) {
var d = new Date(+date);
d.setUTCHours(d.getUTCHours() - 8);
return ('0' + d.getUTCHours()).slice(-2) + ':' +
('0' + d.getUTCMinutes()).slice(-2) + ':' +
('0' + d.getUTCSeconds()).slice(-2);
}
document.write('Current PST time: ' + getPSTTime(new Date));
There is moment-timezone which adds functionality to moment.js for IANA time zones. For PST you can use America/Los_Angeles, however it might also automatically adjust for daylight saving so you'll get PDT when that applies. If you want ignore daylight saving, use the above or find a location with the offset you need and use that.

Javascript Date utcoffset and adding minutes

What am I doing wrong here ?
I cannot get this to matchup with the current UTC time, after I enter my current time as userPickedTime.
userPickedTime = new Date();
userPickedTime.setHours(3,30,0);
userTimeChoiceConvertedToUtc = new Date (userPickedTime.getTime() +
(3600000*userPickedTime.getTimezoneOffset()));
The timezoneOffset is in minutes, you shoul ddo:
userTimeChoiceConvertedToUtc = new Date (userPickedTime.getTime() +
(userPickedTime.getTimezoneOffset() * 60000));
While Raul is correct that the offset is expressed in minutes and you are using the wrong multiplier, you really shouldn't add the offset to the timestamp. The result will be a different point in time entirely.
The timestamp is already in terms of UTC, and the Date object constructor expects that you are passing in milliseconds from the epoch, also in terms of UTC.
You should just use the getUTC... functions, or the toUTCString, or toISOString functions instead.
If you desire more specific formatting of UTC values, consider using the moment.js library.

Getting current date in milliseconds (UTC) (NO use of strings)

Well, you might think that this question has already been asked, but I think it has not. The solutions I've read about all had this "jigsaw puzzle" technique (like getUTCMonth() + getUTCMinutes + ...).
But as I only want to compare the elapsed seconds between two UTC (!) dates, this does not apply.
As everybody knows, you can get the current (non-UTC) date by:
var d = new Date();
var t_millis = d.getTime();
But this is NOT what I want. I'd like to have the current system date in UTC and in milliseconds, so not mess about with strings at all. AFAIK the variable t_millis will contain the millisecond value of the current timestamp in GMT, not UTC.
(Since d is in GMT as well. Unless getTime() does a sort of implicit time zone conversion, i. e. adding the offset BEFORE giving out the milliseconds, but I've never read about that anywhere)
So is there really no other way than adding the offset to the time value?
I'm desperately missing a function like getUTCTimeMillis() known from other languages.
This is an old question but for the sake of the new visitors here is THE CORRECT ANSWER:
Date.now();
It returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC
The millisecond value of the time-of-day is going to be the same regardless of your time zone. That is, there are no time zones on planet Earth that differ from one another by a number of milliseconds greater than zero. (They may differ by an integer number of hours or even minutes, but not seconds or milliseconds.)
That said, the value you get back from getTime() is a UTC-relative timestamp. If two web browsers at widely different spots on the globe create a Date object at the same time, they'll both get the same value from .getTime() (assuming the clocks are synchronized, which is of course highly unlikely).
Here: 1338585185539 That's a timestamp I just got from my browser. I'm in Austin, TX, and now it's 4:13 in the afternoon (so that timestamp will be from slightly before that). Plug it into a Date instance on your machine and see what it says.
(edit — for posterity's sake, that timestamp is from 1 June 2012.)
how about:
var now = new Date();
var utc_now = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
console.log('UTC: ' + utc_now) // correct UTC time but wrong timezone!
console.log('UTC (in ms): ' + utc_now.getTime())
I have used this function to solve the problem.
function getUTCNow()
{
var now = new Date();
var time = now.getTime();
var offset = now.getTimezoneOffset();
offset = offset * 60000;
return time - offset;
}
The getTime function returns the number of milliseconds elapsed since
1 January 1970 00:00:00 in the client timezone.
getTimezoneOffset return offset in minutes between Client timezone and UTC.
offset = offset * 60000; this operation transform minutes in miliseconds.
subtracting the offset get the number of milliseconds elapsed since 1
January 1970 00:00:00 UTC.
To get the timestamp from a date in UTC, you need to take in consideration the timezone and daylight savings for that date. For example, a date in January or in July could mean 1 hour difference.
The option below does just that.
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
It can be used as in:
var date = new Date();
var timestamp = date.getUTCTime();

Categories

Resources