I want the user to enter an appointment date and time and send him a reminder an hour before it.
On the server I want to store the date-time in UTC, but on the client the user will enter it in his local time. Whats the best way to deal with this conversion?
Is there a plugin that natively supports this?
Yes, there's a plugin which detects the timezone according to the system-information (jsTimezoneDetect). Actually a date-object itself stores the information (but it's kinda wierdo!).
There's an interesting article and an interesting answer here on SO, which is worth a read!
Don’t do any date-time computations in javascript. You may guess the
browsers time zone to define it, but the definition itself and all
date-time computations must be made in a time-zone aware system.
As you will read this article, you'll get a deeper understanding of the problem "date/dst/utc/timezones in javascript" - therefore it would be interesting if you tell us more about your server-side:
Which framework do you use on your server-side?
Do you have any logic for represeting accounts with some settings (eg custom timezone-settings)?
The "correct" approach (which is fail-safe if you have the backend behind it) will be: let the user work with a datetime - in the browser-scope it's more or less "undefined" (no need to find the timezone, offset, or anything alike!). Now you provide this "undefined" datetime information to the server (eg sending the unix-timestamp with a hiddenfield to the server), where you have the information which actual timezone the user is assigned to. So you can now translate this "undefined" datetime-information to a time-zone aware datetime-object on the server-side and assign the information of your account-scope to it (now the "undefined" datetime-object has a local time-zone - eg "Pacific Daylight Time"). Now you can easily do any conversion you want.
The only downside of this approach is, that you will have 2 scopes of defining a timezone (OS of the user and your webapp) - but anything else is fiddling and not fail-safe!
It may be an idea to send a timestamp to your server, using the getTimezoneOffset method to calculate the UTC date/time client side. To convert it back client side you'd send the timestamp, create a dummy date client side to determine the currend timezone offset (the user may have moved to another timezone!) and create a client side date from that information. Client side you'd do something like:
//[client side send]
var d = new Date(), //now
offset = d.getTimezoneOffset()
UTCTimeStamp = d.getTime()+(60000*offset); // send to server
//[client side receive]
var offset = 60000*new Date().getTimezoneOffset(),
localDate = new Date(timestamp + (offset < 0 ? Math.abs(offset) : -offset));
Click here to do a simple test using this idea.
Related
The default timezone in the laravel application is UTC and I'm creating a chat application that needs to show the user the time they are sending and receiving messages. Javascript seems to be very easy to convert the database time to the user's local timezone, I used the moment.js library to do this conversion in Javascript but now I don't want to use Javascript I want to use PHP to do the conversion. The problem with using PHP is that it is not converting the time to the actual user timezone, for example, my timezone is UTC+1 but I can only use UTC in PHP.
This is what the Javascript code looks like:
let time = moment.utc(data.created_at).local().format('YYYY-MM-DD HH:mm:ss');
And this is what the PHP code looks like:
{{date('H:i', strtotime($data->created_at))}}
I want to convert the database time to the user's local time using the user's timezone. The Javascript code works fine but the PHP is not working fine. For the UTC+1 the PHP code is an hour slow.
Don't rely on strtotime() or similar methods that "magically" know what format your date is. They guess. Educated guesses, but still guesses.
Use PHP's family of DateTime classes that are properly aware of timezones without mucking about with system-level settings.
$in_str = '2022-07-13 12:34:56';
$in_date = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $in_str, new DateTimezone('UTC'));
$out_date = $in_date->setTimezone(new DateTimezone('America/Chicago'));
var_dump(
$in_date->format('c'),
$out_date->format('c')
);
Output:
string(25) "2022-07-13T12:34:56+00:00"
string(25) "2022-07-13T07:34:56-05:00"
Lastly, I think you might have it backwards. You should be formatting the date/time for human eyeballs as the last thing before displaying it, eg: in Javascript. Everything for backend computation/storage [eg: PHP stuff] should ideally be in a single timezone, and that timezone should ideally be UTC for consistency's sake.
Javascript also has the benefit of running in the browser where it can access the user's timezone preference which is notably not sent in HTTP requests by default. If you want PHP to know about it, you'll have to write some Javascript to send it anyways.
I need to store datetimes in a mysql database.
These datetimes come from the browser, so users in the US, Europe or Asia or wherever will see their correct times.
In the browser, i have the following javascript code:
var d = new date();
var iso_date_string = d.toISOString();
// produces something like "2017-02-17T19:42:27.100Z"
I send this string to the server which runs PHP, and in my server code I have:
$date = date( "Y-m-d H:i:s", strtotime("2014-02-17T19:42:27.100Z") );
And then I insert this value in MySQL.
Everything works fine, except I don't get the exact time, there is a 1 hour difference between what I store in MySQL and the time I have on my computer.
I think this may be related to taking into account daylight saving times, but I can't find how to do it.
Please advise.
When you always send the UTC datetime to your server and let javascript convert it back when showing, the problem will not occur.
The PHP date will be affected by the Timezone information embedded in the php.ini file.
As far as mysql storage is concerned, you will probably want to use UTC or some other standard not affected by daylight savings to store your datetime in mysql. Then, regardless of which browser reads it, it should get converted back according to their local timezone information.
See this article for further reading:
Daylight saving time and time zone best practices
You can use getTimezoneOffset() to check if it's DST, because it corrects for DST.
I found this solution on
http://javascript.about.com/library/bldst.htm
Setting the correct timezone information in the php.ini file did the trick.
Thanks.
I'm trying to learn from this example:
http://fullcalendar.io/js/fullcalendar-2.9.1/demos/timezones.html
Please also right click on the web page to view the page source.
The only part that does not work now is as follows:
// when the timezone selector changes, dynamically change the calendar option
$('#timezone-selector').on('change', function() {
$('#calendar').fullCalendar('option', 'timezone', this.value || false);
});
It is trying to change the calendar time display based on the selection of different time zones.
I'm not an expert in Javascript and have tried to find FullCalendar's explanations on this but with no luck.
My question:
1) What can "this.value" possibly mean? "|| false"?
2) In the backend of my web application, I use Java web servlet with hibernate 3.6. For the time input (start time and end time), I use LocalDateTime from Java 8 and store it as UTC timestamp in MySQL. Not sure if this is the best practice for a calendar-based scheduler?
3) Currently, I don't have a timezoneId attached to the timestamp stored in the database yet. But I have created a list for the user to choose from as the FullCalendar example did. Any suggestion on what is the best way to store and later use a timezoneId for this calendar display across different time zones?
For now, I'm thinking that trying to totally imitate FullCalendar's example is not very practical because my database is different from theirs. I'm open to any good suggestions on how to get user's current timezone from his selection, store it in database and later display the proper time value based on any timezone selected by the user on his calendar view page.
If you inspect the timezone select you can see that each option has a value. this.value means the on change function will grab the value of the selected option to assign as the timezone. As far as storing your times, they should be stored as UTC timestamp like you are doing. For retrieving the timezone I use jstz to get the users timezone, its as simple as these two lines.
var tz = jstz.determine();
var timezone = tz.name();
This is great because you dont have to ask the user for their timezone. Then when I query my database for events I pass in the timezone
events: {
url: "calendarManager.php?request=get&timezone=" + timezone + "&userid=" + userID
},
and use php to convert from utc to the users local timezone and return the json encoded events.
We have server code that uses DateTime.UTCNow and is serialized as
2015-02-17T12:38:58.3220885Z
What is the correct way to interpret these serialized dates client side, taking time zones into account?
I am trying to track down a reported bug where the times appear to be incorrect and 'in the future' - at the client - I have seen no evidence of this however. The idea is for the server and client to simply be working with the same point in time.
Just do
var date = new Date('2015-02-17T12:38:58.3220885Z');
date.toString()
Will give the date according to the local time zone.
I use these lines of code to find out the local time in Gujarat - India, regardless server time set correct or not. But i noticed that this is not working. This line produce SERVER TIME, but not LOCAL TIME. It cause problem if server time change accidentally.
What is the exact solution to to get LOCAL TIME in any country in the world?
Dim zoneId As String = "Indian Standard Time"
Dim tzi As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(zoneId)
Dim result As DateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi)
You may want to take a look at Noda, a .net port of Joda an open source project for working with dates. This has been ported by Stack Overflows, Jon Skeet.
A couple Link that might be helpful.
http://www.codeproject.com/Articles/78213/Noda-DateTime-Extensions-for-NET
enter link description here
What you want is the correct local time, regardless of the server defined time.
First of all, the server should be configured with the correct date/time. If you can't trust it, I think you have to rely on a service provided by a third party provider to tell you the correct time.
This other question suggests services you can connect to: Web service - current time zone for a city?
If what you want is the client's time, you have to get it through Javascript and send it to the server side.
Good luck!