Convert set date to user's local time automatically - javascript

I am creating an application where I have a pretty big set of dates and times, and I need to display these in the user's local time and date. All set dates and times are in BST; so for example 08-24-2014 16:00 BST = 08-24-2014 11:00 EST. Now, before coming here I spent good 3-4 hours looking for an answer but if anything, I got more confused. Is there any way, to convert a set of BST dates and times to the user's local settings automatically without them setting the time zone etc?
p.s.: I have two ideas in mind but I don't know if they would work nor how to execute them.
1) Get and change the BST date and time and convert it to a unit of measurement; get and change the user's local date and time and covert it to the same unit of measurement as above, calculate the difference in the new measurement, and convert that to the user's local time.
2) Use GeoLocation to find the user's date and time/ time zone and; convert the BST to whatever the GeoLocation spits out.

you can get the users machine timezone in javascript:
var currentDate = new Date();
var currentTimeZoneOffsetInHours = currentDate.getTimezoneOffset() / 60;
see documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
having the offset you can add it to your values

there is a javascript library Moment.js which allows you to query daylight saving values for specific dates and timezones.
because all your dates are in british summer time. first query if a date is in british winter time with isDSTShifted(). and subtract() an hour.
convert the date to another timezone

Related

JS how to add hours and minutes to scheduled date

I need to be able to let clients schedule a certain type of meeting for a future date,
the meeting duration I get back from the database is in minutes.
I need to be able to create a future start date and time, then add the duration minutes to that time and get the end date and time.
Then convert those two to utc time and iso format to send to backend. I know how to convert to utc and iso, just not sure of the best way to add times with the duration being in minutes.
Any one know the best way to do this with javascripts date api, moment.js or another library?
I like to approach problems with time using the date-fns library. Today the Date object solves "most" of our problems so date-fns helps giving useful functions to manipulate dates.
What you might be looking for is the add minutes function. Also the formatISO might help.
For UTC, the UTC method should work fine.
With the Date API, you can:
// hours
date.setHours(date.getHours() + someHours);
// minutes
date.setMinutes(date.getMinutes() + someMinutes);
// whatever else...

will conversion of timestamp to date in different timezones returns different date and time?

I am trying to convert my current date into timestamp and send it to API to save it. When I try to retrive the timestamp back from API and convert it to date, it is retriving coorectly.
The issue is when I send current timestamp to API and if a person in singapore fetch the same timestamp from API and try to convert to date, It shows (date and time I have sent to API)+2.30hr.
I use new Date(timestamp) in javascript to convert timestamp into date.
Similarly it differs to different timezone.
How can I solve this issue?
You can use UTC time to standardize between various locations and send it in your api, and when someone wants to work in singapore receive the datetime in UTC and then convert it to his local time-zone.
var utcDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0));
The constructor of Date.UTC
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
Unix like timestamps in Javascript are the number of milliseconds since Jan 1 1970 with no time zone offset. Date.now() returns such a timestamp.
If you send "your date and time" to the API as a timestamp, retrieve it and convert back into "date and time" in a browser on your PC, the conversion back will be from UTC into local time as defined by the local zone setting of your PC. Somebody 2.5 hours west of you, with a local time 2.5 hours later, will convert the same UTC timestamp into a local time value 2.5 hours later than yours.
How to resolve the issue depends on what needs to be achieved. Should global users see timestamps in your timezone, UTC, their timezone, a timezone specified on the website, or relative to a given location, such as the departure and arrival airports of aircraft flights? This needs to be decided first, before looking into Date object methods with "UTC" in their names :-).
In response to comment of using OP's timezone:
If your location does not use daylight saving, you could include your fixed timezone offset in page script and use it in conjunction with users' timezone to produce a date and time string matching your local time of creation. A problem if daylight saving is introduced to your area in the future.
For daylight saving, you could add your easterly time zone offset in milliseconds to a Date.now() time stamp, store the result in the API, retrieve the timestamp and convert into a date and time string using the .getUTCxxx methods inherited from Date.prototype. Such a conversion should match your local time when the timestamp was created. The method may have valid criticisms but at least should meet with requirements!
Ideally the UTC timestamp would be stored unchanged, and the local timezone offset of the creator stored as well.

Is there a simple time to get a timezone from a given time?

I need to get a timezone from a time, date is not important, but daylight savings is.
something like:
timezone = function("15:00");
Is there a simple way to do this?
I dont think you can get the timezone from the time but you might get some help from Date.prototype.getTimezoneOffset()
The getTimezoneOffset() method returns the time-zone offset from UTC,
in minutes, for the current locale.
Example:
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
No, of course not. Think about it, you're passing 15:00 to that function, presumable denoting it's 3PM. But in what timezone is it 3 PM? No way of knowing. It's like me saying it's quarter to, without saying what hour it's quarter to to.
The only way you can get a timezone in JS is by using the Date object, but that just shows the timezone of the machine on which your code is running, nothing about the TZ that "created" the time you're processing.
Also note that daylight saving isn't a global phenomenon, quite the contrary. AFAIKT, there isn't a single time-zone where DST has always been in place...
In order to get TimeZone information you need more than a Date (and an offset). You need a location.
Javascript does not know the location that it resides in but it does know the current offset from UTC. That is different than a Time Zone. The daylight savings time issue play havoc with this key difference.
This has posed problems when dealing with server applications that know their timezone and report dates as being in a specific Time Zone.
My rule of thumb has been fairly simple in this regard.
Always use Long or long (a 64 bit number) to store, pass and process dates times or intervals, only convert to Date, Calendar or DateTime objects when interacting with people.
Once you have a date object, such as with new Date(), you can use .getTimezoneOffset() to get the number of minutes between the date's object and UTC, which is timezone information you can use.

Deal with timezones in JS from UNIX timestamp

I'm currently writing a small messaging app for global usage. I'm going to store the UTC timestamp of the message. I need to display the message to the user using AJAX, so i need to convert the UNIX timestamp to the users local time. I know how to get the timezone offset, but i'm afraid that it will be a little bit inaccurate and i need accuracy even in seconds (to display times like: 34 seconds ago). Which is the most accurate way to solve this?
Why not calculate the local date locally? Constructing a date with new Date(millisecondsSinceEpoch) locally and then calling toTimeString() (or whatever) should show you the local time:
new Date(milliseconds).toTimeString()
var d = new Date((new Date(1390312399000)).toUTCString());
Where the timestamp is the stored UTC timestamp.

javascript timezone converter

I need a way to convert times in the future to different timezones without relying on the user's computer time.
At registration time, the user supplies his timezone. When he logs in, I calculate the offset in minutes between the UTC time and his time and inject that offset into the page so that a javascript function can do the conversions. Something like this:
var TheUTCTime = new Date(UserTime.getTime() - TimeZoneOffsetInMinutes * 60000);
and like this for the other way around:
var TheUserTime = new Date(UTCTime.getTime() + TimeZoneOffsetInMinutes * 60000);
This works really well to convert times as long as the offset doesn't change. For instance, because of daylight saving, between US EST and UTC, there's a difference of 300 minutes or 360 minutes depending on the month in the year.
My functions work well to convert today's date but I'd like something that can 1) do the same thing for any day of the year and 2) doesn't depend on the user's internal clock or timezone.
How could I do this?
Thanks.
My functions work well to convert today's date but I'd like something that can 1) do the same thing for any day of the year and 2) doesn't depend on the user's internal clock or timezone.
If you want to convert another UTC time into the user's local time, you have to know their time zone. That's pretty much the definition of a time zone: a mapping between UTC and local time (or equivalently, between UTC and the offset from local time).
As you've seen, getting the current offset isn't enough, because of daylight saving transitions (and any other changes to time zones - they vary more than you might expect).
Basically there's no way round this: you will have to ask the user for their time zone. You can make a good guess based on the current offset from UTC and possibly geocoding their IP address, but you'll have to confirm it with them. (For example, they may be on a trip or something, and not in their "home" time zone.)
To don't depend on the user's clock timezone, I think the best approach is to do conversions in the server side.
There's a good question here in the SO that covers daylight saving time and javascript Date object: Daylight saving time and time zone best practices

Categories

Resources