Javascript Stored Date Between Timezones - javascript

I've been looking for a solution to this but as yet I've not found exactly what I'm looking for. I have the following issue:
A user selects a time in my react-native app. I store this in an SQLite DB as a datetime.
The user can edit said stored time and the DB is updated.
When the user selects a time from the input, a date is constructed from it and the time is outputted on-screen to show their selection after dismissing the input.
This all works OK if my user is in one timezone.
Unfortunately, if the user were to travel to another timezone the DB value is adjusted and the wrong time is displayed on the edit screen.
So, if I select the following on my form: 7:00am
My DB will store (for example) Sun Oct 01 2017 07:00:00 GMT+0100 (BST)
If however, I move my timezone to Tokyo and edit the time in my app, it is adjusted and shows a different value to 7:00am.
Here is the code I use to construct the date that is passed into the DB:
var date = new Date(Date.parse('2017-10-01T' + hours + ':' + mins + ':00Z'));
var _ofst = date.getTimezoneOffset() * 60000;
date = date.getTime() + _ofst;
(where date is stored)
Now, I know the offset is going to skew things but if I don't use it, my on-screen feedback to the user is adjusted to 8:00am due to my local current timezone.
What I want to do:
As an example, when a user selects 7:00am:
it should show this on screen correctly when a user picks a time (e.g. 7:00am)
it should store this in the DB correctly (Sun Oct 01 2017 07:00:00)
if the user moves timezone, I don't want it to adjust the stored value. (I want 7:00am to be the time used in-app)
I know I could use string manipulation to extract the stored time from the DB and re-construct the date on the way out but I am wondering if there is a less hacky approach which will maintain the chosen time regardless of where the user is in the world.
I want to use this time for notifications so if a user picks 7:00am they should see the notification at 7:00am.
Update
I think I've found a good way to manage this using moment.js which handily is part of node_modules in React-Native.
By using:
var date = moment('2017-10-01T' + hours + ':' + mins + ':00Z').utc().format();
I can ensure that the date stored in my DB is:
2017-10-01T07:00:00Z
This means it isn't 'polluted' by any offset data and when I bring it back out of the db I can use the same moment code to recreate my non-offset datetime.
Initial tests are proving successful using this method. All hail moment.js!

You are way overthinking things here.
If you don't want the time to adjust for timezone.. simply don't adjust.
A timezone anchors your time to a geographic location. You don't want that.
Store the selected time (e.g. 7:00 am) without a timezone, and just compare it to the local time.

Related

Simplest way to find out how many milliseconds until a specific time in a specific timezone (taking DST into account)?

I have a piece of code which finds the difference between two dates(in the format of yyyy-MM-dd hh:mm:ss) . This code is run in multiple servers across the globe. One of the two dates is the current time in that particular timezone where the code is being run(server time) and another is the time obtained from a database. if the difference between these two times is greater than 86400 seconds(1day), then it should print "invalid" else, it should print "valid".
Problem im facing with the code is when I run it on my local, its working fine, but when i deploy it onto a server in US, its taking GMT time into consideration and not local time.
Wherever the code is run, I want the difference between current time and time fetched from the database, and if its greater than 86400 seconds, i want to print invalid. How to achieve this in java?
PS: I tried with Date object, but its considering GMT only everywhere.
I would use GMT everywhere and only convert to the local times for display purposes.
To find the difference, convert both times to the same timezone (say GMT) and take the difference.
You can do it by the below example code.
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
Date date1 = dateformat.parse(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
Date date2 = dateformat.parse(formatter.format(date));
// Prints the date in the IST timezone
// System.out.println(formatter.format(date));
Now compare date1 with date2
First, I concur with Peter Lawrey's answer up there. It is usually good practice to store all time in the database for a single zone, and render it with offset for the user based upon the user's locale.
To find the difference, use the method getTime() to get the time in milliseconds from the epoch for each date. The calculation for the difference of 1 day is then 86400 * 1000 milliseconds. Or, perhaps, store the time in milliseconds from epoch in the database, and use a DB procedure/function at the time of retrieval.
Hope this helps.

Issue converting Luxon date to a selected Time Zone from user cookie

I am working on a web application that needs stores a start and finish value for a work shift. The application has a timezone selection component which updates any date/time values in UI to match the time in a given timezone/location by changing a timezone cookie. Values are stored in a database as UTC values and they are passed through a controller to convert them between the DB and UI.
I am working on a page that has an exception where the start and finish times are changeable/editable by the user after saving. The page will get these values from UI Date Boxes. The values can convert to UTC on saving values with no issue with use of Luxon, however, a user can navigate back to the given page to edit saved values if changes are needed. When this happens, the saved values are loaded into these DevExpress/DevExtreme date boxes but they are not displayed as expected.
The values come from an odata response and is read as response.value[0].Start. When getting the value, an offset is applied based on the users cookie location, so in my case (Europe/London timezone) the response would be 2022-05-24T01:00:00+01:00.
I can convert this to UTC using DateTime.fromISO(response.value[0].Start).toUTC() to give me a value of 2022-05-24T00:00:00.000Z which is expected.
However I am running into converting this value to the desired value for a selected timezone. I try to do so with the following:
var DateTime = luxon.DateTime;
//selectedTimeZone found from cookie.
// -- logic --
if (response.value[0].Start != null) {
var dateBox = $("#ShiftBeginning").dxDateBox('instance');
var converted = DateTime.fromISO(response.value[0].Start).toUTC().setZone(selectedTimeZone, {keepLocalTime: true});
dateBox.option({ value: converted});
}
//Example selectedTimeZone: Asia/Tokyo
//converted.toString() value: 2022-05-24T00:00:00.000+09:00 (Tokyo time zone)
//Displayed UI Time value: 16:00
//Displayed UI Time value with {keepLocalTime: false}: 01:00
It appears as if the value of converted is having the offset applied twice, with an hour then taken off of the time to represent UTC.
I have tried changing parsing this value to different formats, tested different timezones, using standard JavaScript Date object etc. and I am beginning to run out of ideas.
Any help is appreciated to help solve this.
It's being "converted" twice because the time picker doesn't respect the zone in your cookie, because it doesn't know about it. Remember that the time is the time; the zone and how the time is represented in that zone are more like metadata. So it's expressing the time in user's system zone, and the local time it displays is off from what you expect by the difference between where they are and Tokyo's local time.
What you want to do is:
find the local time in Tokyo for your time. This is probably just DateTime.fromISO(s).setZone(selectedZone). You don't want keepLocalTime because your time is correct
change to the user's system zone, but keeping the time constant, which is just converted.setZone("system", { keepLocalTime: true }). We do this because we want a local time that is, technically, wrong; it's what local time matches the right Tokyo time. This is more-or-less the purpose of keepLocalTime: to trick zone-unaware components into showing a local time in another zone.
It's a little odd that you're passing the Luxon DateTime directly to the time picker. I guess it's calling valueOf() on the value you pass in. But you'd probably want to do that yourself to be confident you're telling it the right thing.
So all together:
var converted = DateTime
.fromISO(response.value[0].Start)
.setZone(selectedTimeZone);
.setZone("system", { keepLocalTime: true });
dateBox.option({ value: converted.valueOf() });

How to save correct time in database?

I have one object called appointment which has two properties: StartDate and EndDate.
When I make POST request I send these values using ISOString time .
this.appointment.StartDate.toISOString()
On the server-side, I received these properties with correct values. Also, it seems to be correct when I create model in order to save appointment to the database. I used .ToUniversalTime() method.
var newAppointment = new Appointment()
{
StartDate =Convert.ToDateTime(model.StartDate).ToUniversalTime(),
EndDate = Convert.ToDateTime(model.EndDate).ToUniversalTime(),
SpecialityId = speciality.Id,
LocationId = location.Id,
PatientId = patient.Id,
UserId = user.Id,
Observations = model.Observations
};
But in database I found another values. Can explain somebody why is this behaviour ?
For instance, I used 2017.09.01 11:00 for StartDate and in database i found 2017-09-01 08:00
The server and database is located in the westeurope.
A few things:
Don't call ToUniversalTime in a web application. It's designed to convert from the server's local time zone to UTC. The server's time zone should be irrelavent to your application. Web applications should never use ToUniversalTime, ToLocalTime, DateTime.Now, TimeZoneInfo.Local, DateTimeKind.Local or any other method that uses the time zone of the computer it's running on.
Ideally, on the server side, your model.StartDate and model.EndDate would already be DateTime objects, because they'd have been deserialized that way. Therefore, you probably don't need to call Convert.ToDateTime. If they are strings, then I would adjust your model class accordingly.
On the client side, assuming StartDate and EndDate are JavaScript Date objects, and they were created using local time values (that is, the time zone of the browser), when you call toISOString, you're not just getting a string in ISO 8601 format - it is also converting it from the browser's time zone to UTC.
In your example, the UTC time is 3 hours ahead of UTC for the date and time shown. From your profile, I see you are located in Romania, which is indeed UTC+3 for this date, because it is currently observing Eastern European Summer Time. When Summer Time ends (on October 29, 2017 at 04:00), it will return to UTC+2. For this reason, you cannot simply add three hours to all values.
If you want to send local time values from the client, you should send them in ISO 8601 format, without any Z or offset, for example 2017-09-01T11:00. There are several ways to achieve this:
The best way is to not have them in a Date object to begin with. For example, if your input uses the <input type="datetime-local" /> input type (as specified in HTML5), the .value property is not a Date object, but rather a string in ISO 8601 format.
If you can't avoid a Date object, then create a local ISO string, like this:
function dateToLocalISOString(date) {
var offset = date.getTimezoneOffset();
var shifted = new Date(date - offset * 60 * 1000);
return shifted.toISOString().slice(0, -1);
}
OR, using Moment.js:
moment(yourDateObject).format("YYYY-MM-DD[T]HH:mm:ss.SSS")
Lastly, you will probably read advice from others about storing these as UTC. Don't listen. The advice "always use UTC" is shortsighted. Many scenarios require local time. Scheduling appointments is a primary use case for local time. However, if you need to act on that appointment, you'll use the current UTC time, and you'll also need some information about the time zone for the appointment so you can convert from UTC to the appointment's time zone. For example, if this is something like an in-person doctor's office appointment, then it's safe to assume the time zone of the doctor's office. But if it's an appointment for an online meeting, then you'll have to capture the user's time zone separately and apply it on the back end where appropriate.
The problem is with your current timezone.
What your application does is get current timezone (+3) in this case.
Now it got your timezone but it will convert to utc time. So what will happen, your current time will be -3 hours.
If you not adjust to summer and winter time then you can simply add 3 hours to the datetime. Otherwise you have to get the offset of your timezone and add that to the current datetime value.
Take care if you use this application in different timezones. For example You life in +3 and some else life in +2 timezone.

Momentjs Grabbing today's date and setting time causes it to fast-forward 24 hours

I'm trying to time out email messages based on user preferences. My morning calculations are working correctly but it's the evening emails that are never getting sent because dates aren't behaving as expected.
First, here's the code I'm using to grab the time and perform adjustments based on user location, etc.
var time = moment();
var machineTZ = time.zone();
var userTZ = 420;
var diffTZ = userTZ - machineTZ;
var oneHour = moment(time).add('minutes', 60);
var morningRun = moment().startOf('day');
morningRun.hour(7).minute(0);
morningRun.add('minutes', diffTZ);
var eveningRun = moment().startOf('day');
eveningRun.hour(19).minute(30);
eveningRun.add('minutes', diffTZ);
I'm checking every hour to see if it's time to schedule another email to go out. Right now this is hard-coded, but when I begin to add user preferences they'll be able to select their local time they'd like things to go out at.
I've been debugging my values to troubleshoot. Here's output from a job that ran early morning (from the server's perspective):
lastRun: 2013-10-12T00:06:55.088Z (this one is being run at 1 am)
morningRun: 2013-10-11T14:00:00.000Z
eveningRun: 2013-10-12T02:30:00.000Z
The run numbers are as I would expect them to be. In two hours time I want the evening email to go out (7:30pm my time = 2:30am the following day server-time).
Looking again an hour later we see:
lastRun: 2013-10-12T01:06:58.267Z (this one is at 2 am)
morningRun: 2013-10-12T14:00:00.000Z
eveningRun: 2013-10-13T02:30:00.000Z <---- what?
All of a sudden my calculation for my evening has flipped over the date line, even though it's still 10/12 (not 10/13 yet). Because of this my check to see if I should schedule the email fails since it now thinks I need to send the email in 24 hours, not 30 minutes.
Been battling with this weird inconsistency for a while, I thought I had figured out why it was doing it and adjusted my calculations using the time zone stuff above but that didn't do the trick :(. This certainly seems like some sort of weird bug as I would expect this to be happening:
//Today is 10/12
var eveningRun = moment().startOf('day'); //10/12/2013 - 00:00:00
eveningRun.hour(19).minute(30); //10/12/2013 - 19:30
eveningRun.add('minutes', diffTZ); //10/13/2013 - 2:30 am
This works until at some point it decides that "today" is actually 10/13 and sets the evening run is to take place on 10/14 instead. Help is greatly appreciated, or if this is a bug would love to know what I can do to work around this issue until it's resolved.
There's no need to calculate machineTZ, diffTZ or add any minutes. Just do this instead:
moment().zone(userTZ).startOf('day').hour(7).minute(0)
But do keep in mind that a value such as 420 is not a time zone, it's a time zone offset. It only tells you what the offset is for a particular point in time. Since you are applying it unilaterally, you may get incorrect results during daylight saving time.
Instead, you should try using the moment-timezone addon, and do something like this instead:
moment().tz("America/Los_Angeles").startOf('day').hour(7).minute(0)
See also the timezone tag wiki, in particular the sections titled "Time Zone != Offset" and "The IANA/Olson Time Zone Database".

Javascript countdown using absolute timezone?

I have a javascript countdown timer that works by taking a specified date and time, and comparing it to the current date and time. The issue is, the current time is relative to the users timezone, so the time remaining is different between users.
How can I have the timer countdown till a time in a specific timezone, in my case GMT -5 hours?
I understand i can use the below code to get the users timezone, but I am lost as how to use this.
myDateObj.getTimezoneOffset( ) / 60
You can use Date.UTC(year,month,day,hours,minutes,seconds,msec)
It operates just like the Date constructor, but returns the timestamp of the arguments at Greenwich time (offset=0) instead of local time.
var localtime=new Date(Date.UTC(year,month,day,hours,minutes,seconds,msec))
returns the local time for the UTC time specified.
Everyone (whose clock is set correctly) will end the countdown together.
A quick search reveals: convert-the-local-time-to-another-time-zone-with-this-javascript
Following the article verbatim gets you this example:
var d = new Date();
var localTime = d.getTime();
var localOffset = d.getTimezoneOffset() * 60000;
var utc = localTime + localOffset;
// obtain and add destination's UTC time offset
// for example, Bombay
// which is UTC + 5.5 hours
var offset = 5.5;
var bombay = utc + (3600000*offset);
var nd = new Date(bombay);
alert("Bombay time is " + nd.toLocaleString() + "<br>");
jsFiddle: http://jsfiddle.net/GEpaH/
Just update with your desired offset and you should be all set.
Just create a Date with an RFC 2822-timestamp with timezone. That time will then be converted to the users current location (based on OS settings). Even with corrections for daylight savings time!
I'm in Norway, which currently is in daylight savings time, so it's GMT+2. Here is what happens when I create a Date object using GMT-0500:
var myDateObj = new Date("Fri Apr 17 2015 12:00:00 GMT-0500 (CDT)");
myDateObj.toString();
Fri Apr 17 2015 19:00:00 GMT+0200 (CEST)
How to get the correct date string for your location? If it's the timezone you're currently in; just do myDateObj.toString() in your browsers dev-tools console. For a different timezone; change the timezone in your operating system first. (Or read the RFC)
new Date().toString();
Fri Apr 17 2015 12:36:57 GMT+0200 (CEST)
You don't really say exactly what your are trying to accomplish. The javascript date object retrieves the local time and the "timezone offset" (relative to GMT (UTC)). These are of course "set" by the user so even if in the same time zone, two users are very unlikely to have the same "time".
If you are trying to time between different users you need to be referencing some centralized time authority.
I would use an AJAX type call (XMLHttpRequest) to a page own my own server that returns my server's time. That way each user is referencing the same time.
Google XMLHttpRequest to find examples of the JS code you need (and oftentimes the corresponding server-side code for a simple service such as this).
PS: I would also install some simple client software to keep the time on my server accurate by synching with an atomic clock every 10 minutes.
You can't get an accurate date with JavaScript as it is client-side and it is based on the user's operating system clock. You can use jCounter to display countdowns based on server-side timezones.
But hey, if you really want to do it yourself, download jCounter and you'll find a dateandtime.php file as well which retrieves the current date server-side, as timestamp (it will have to be placed on a server btw, not on your desktop :P)
Check how that script uses that file and retrieves the real current date to operate against it and calculate accurate countdowns.
Cheers
To revise the approach Brandon has taken to calculate a UTC-shifted time, we can slim the code down into a two-line extension of the Date object:
/* getOffsetDate - Returns a Date shifted by a certain offset
* #param offset the UTC offset to shift, in hours
* #return new date object shifted by UTC offset
*/
Date.prototype.getOffsetDate = function( offset ) {
utc = this.getTime() + (this.getTimezoneOffset() * 60000);
return new Date(utc + (3600000*offset));
}
You can then calculate the UTC-5 shifted date as follows:
myDate = new Date().getOffsetDate(-5);
It should be noted that extending native prototypes in this manner is generally considered a bad practice since it muddles core objects that other libraries depend upon. To justify it, you'd have to argue this functionality should be a native part of the Date object.

Categories