This question already has answers here:
Should I use the datetime or timestamp data type in MySQL?
(40 answers)
Closed 9 years ago.
I have searched around and haven't found a specific answer to my question..
I am wondering the best practice for storing timestamp information.
Example:
user1 logs in in Florida (-0500) at 3:00pm EST
The admin logs into the system an hour later from California (-0800) at 4:00pm
I want the admin to see the log onscreen and see that user1 logged in 1 hour ago..
My brain is going nuts bc i feel that i am over complicating this..
I should be able to use UNIX time stamp and then adjust with the -0800 or -0300.
Do i store the users timezone offset in their profile information?
Do i store the -0300 with the log entry.
Any input would be greatly appreciated!
You are mixing up client timezone and server timezone.
As long as you do not care where your users sit, you have absolutely no problem as long as you do not change the server timezone. You can set a default timezone in MySQL and in PHP and this one will be used, independent of the timezone of the visitor.
If you want to respect the timezone of your visitors, it gets slightly more complicated. You need do transform a timestamp from one timezone into another. You can find information concerning that in the PHP manual if you want to achieve this with PHP. You can read this SO thread if you are interested in how MySQL stores dates internally (difference between TIMESTAMP and DATETIME type), which opens the possibility to use some of mysql's features, and which you should definitely take into account when you implement a global project.
Timezone can be configured dynamically in the PHP, so you don't need to store time offsets in your DB. Storing unix timestamp is a good solution.
You can store timestamp as INTEGER datatype.
Then, you can use JS on client side to get the timezone of user.
Related
I ran into trouble while dealing with date and time using php and mysql. I am trying to store local time of user's timezone as a timestamp on mysql db and would like it to convert back to normal date and time at the time of output.
This is the first time I am dealing with date and time.
As I understand: I can't rely on PHP's time() as it returns servers time according to server's timezone and the same case with mysql current_timestamp.
I can use the javascript to get user's local timezone and then can use date_default_timezone_set() for each session.
If I am doing right, now the confusion starts.
As you can understand the users will come from around the globe, so if two users (one from US and another from India) do something at the same time, will it show each others time as identical or it will show some difference? I mean it shouldn't show Indian user that the US user has done something few hours ago as the US user done at same time.
Please let me know if I don't understand these things properly.
What I want to achieve is, the output of the time should show in local time format. Ex: any time should show in IST format for Indian user and other country respectively.
Best way to achieve this is to store date in a database in a standard format (eg. GMT).
After getting user's timezone through javascript, you may convert date to user's timezone & display accordingly.
Well I know that this question may be asked many times but certainly I've few doubts In my mind, and by the way don't comment that what I've tried, I've tried many ways but am just asking what's the correct and easier way as there are many posts lingering out here with different suggestions for accomplishing these tasks, so I'll explode() my question into smaller questions...
So can you people just guide me where am going right or wrong as am sure many people are confused when it comes to date/time
1) Why/how to save time as UTC in MySQL using PHP?
Personally for this I post this using php $year/$month/$day and check the date using checkdate() in mysql date field. so is it ok or should I use timestamp and than explode the retrieved string on front end using php?
2) If I run server from India, should I record default time using date_default_timezone_set("Asia/Calcutta"); and than subtract and add time using php function or while posting only I should check users time zone selected from his user accound and accordingly set a condition kinda:
if(timezoneselected == +5.30) {
echo date_default_timezone_set("Asia/Calcutta");
} elseif(timezoneselected == +anytime) {
echo another country timezone
}
3) last question is how websites like gmail facebook etc manages time? I mean if they are saving datetime according to their server than how they show perfect posted time for each user, even gmail, if I send a mail to another user, my sent time and the person living in another country gets email at his printed local time I mean how we can do this, sorry am not able to explain you perfectly say this example,
facebook:
user from India posts, facebook shows posted 8 mins ago, 9mins ago, fine after sometime they show a real date, and that date is perfect according to the time I posted, however if a person from USA updates, say 8 mins ago 9mins ago on his profile but his original posted time is shown correctly to him, and even correctly to me?
sorry for this question but really this will help me understanding this date/time concept and will also be helpful to future users. Thank you!
Bottom line, you should store everything UTC
When you display times for a particular user, use a timezone of their choosing. Store the timezone of the user, like "Asia/Calcutta" and simply convert the time when displaying it using the date_default_timezone_set method.
I will attempt to answer your questions from the comment here.
You store everything UTC always. It is the baseline. When you display the times associated with anything you convert based on the user. If you want to display Posted 8 mins ago then you are taking the delta between the current UTC time and the UTC time associated with a post. If you send a message from user A (in India) to user B (in Los Angeles, USA) then you would store the message time in UTC. If user A is viewing it, the time would be converted to "Asia/Calcutta" and if user B is viewing it, the time would be converted to "America/Los_Angeles". Using UTC will make your life a lot easier. Trust me.
As described in MySQL Server Time Zone Support:
The current session time zone setting affects display and storage of time values that are zone-sensitive. This includes the values displayed by functions such as NOW() or CURTIME(), and values stored in and retrieved from TIMESTAMP columns. Values for TIMESTAMP columns are converted from the current time zone to UTC for storage, and from UTC to the current time zone for retrieval.
Therefore, if you use TIMESTAMP type columns, MySQL will handle timezone conversion for you automatically: just set the appropriate timezone for the session in its time_zone variable.
I need some guidance with one of my project requirements, I am developing an application which has to deal with various time zones.
Scenario:
User 1 is from India, so his time zone would be GMT+05:30
User 2 is from UK, so his time zone would be GMT+01:00
If the User 1 sends a message to User 2, I want to show the Message Sent/Received Time as per the user’s time zone. For example User 1 sends a message at 6:30 Indian time, when User 2 would view the message it would show as 2:00 UK time.
Here goes my question, whenever I save the message should I convert it to GMT+00, so all my base times stamps are the same and then later when I display the message, I convert it back to User specific time zone. Would this be complex? Is this the best way of doing this?
I like to get views for both saving and displaying, also when I should do the time conversion from optimization point of view. I would need do deal with any/all timezones.
I am developing this application with PHP and MySQL and I am aware of timezone conversion method come with both PHP and MySQL.
I am just trying to figure out the best way of doing this. Look forward to have all valuable suggestions.
Note : As of now I am not much worried with day/light savings.
Thanks
Ravi
When storing the messages, convert, use and store them in a DST neutral timezone - UTC or GMT, for example.
With them store the original timezone offset and the DST offset - this will help with business logic.
When displaying the message, use this data and convert to the local time.
See this question and answers for best practices regarding working with different time zones.
Here goes my question, whenever I save the message should I convert it to GMT+00, so all my base times stamps are the same and then later when I display the message, I convert it back to User specific time zone. Would this be complex? Is this the best way of doing this?
It is. The only caveat is to allow each user to specify their desired timezone to view times in (either as a preference or from their client system's settings or from user database).
I like to get views for both saving and displaying, also when I should do the time conversion from optimization point of view. I would need do deal with any/all timezones.
The best time to convert from client to GMT is in your "business" logic - basically, whatever logic you have which processes web form data. NOT on the database side.
The best time to convert from GMT to client for viewing is right before/in the presentation layer, e.g. when you're printing your HTML.
The reason is that this way, as little of the code as possible needs to worry about timezones.
NOTE This timezone related logic becomes VERY VERY complicated if/when you need to do any date-specific logic (e.g. aggregate based on date as opposed to merely print timestamp to the user).
When saving data to your database, use something like:
INSERT INTO TableName SET TheDateFile=UTC_TIMESTAMP()
And then, presuming that you allow each user to specify their own timezone, you will need to convert the date in your business logic (as mentioned by DVK)
Something like:
DATE_FORMAT(DATE_ADD(TheDateField, INTERVAL 2 HOUR) // or whatever value
I have not done this myself, but I guess it would be simple enough to store the hour interval as per the users timezone.
In any case if you deal with users which are on different timezones, you must separate the timezone from the date. I heard long time ago that wordpress did it the same way:
First step, determine timezone of the date
Second step, set the timezone of the date to GMT (+0)
Third step, store the timezone and the GMT date in two separate columns.
Anyway, if you need more informations, there's a post here
I have gone through many timezone/PHP posts, and most suggest storing your datetime fields in UTC, then using the application users timezone offset when storing and displaying datetime information.
The problem i have I've inherited an application that wasn't timezone aware, and now I need to cater for this.
The server is already set to "EST +11:00 Australia/Melbourne", and there are already applications running from that server. So i can't change this.
Fortunately, I do know a users timezone offset, ie -05:00, etc,.
The application takes Javascript Dates and parses them using PHP's strtotime() function and stores in a MySQL database, like this:
$event_starts = date('Y-m-d H:i:s',
strtotime('Thu Dec 02 2010 11:15:00 GMT+1100 (AUS Eastern Daylight Time)');
So does anyone have any suggestions for the best way on how I can make this application timezone aware considering the server isn't set to UTC?
Many thanks, J.
This is not going to be very easy.
First of all, consider that existing stored dates are in local time of your server, which observes daylight saving time. Any code that has to do anything with these dates except just printing them, now or in the future, will need to convert them to UTC first. If the daylight saving rules are not exactly the same at the point in time where the date was stored and the current time (when the conversion is taking place), your server will use the "current" rules and therefore produce a wrong result. Granted, this scenario may be far-fetched in your specific case (or then again it might not), but it's a very strong warning against storing anything other than UTC.
Assuming that the DST rules remain constant, and that you have PHP >= 5.3.0, you can do this:
Read "original" database date with DateTime::createFromFormat, explicitly specifying the timezone (server's TZ)
Convert to user local time with DateTime::setTimezone (specifying user's TZ)
Display to the user
When receiving user input, you will need to do the reverse:
Create user local time date with with DateTime::createFromFormat, explicitly specifying the timezone (user's TZ)
Convert to server local time with DateTime::setTimezone (specifying server's TZ)
Store in database
Apart from the above, I would suggest taking your application offline at some point and convert all dates in the database to UTC. You would then be rid of the problem discussed earlier (at least in the future, as the past cannot be undone). The "server's TZ" I mention above would then be UTC (regardless of the fact that the actual server may be set to AUS EDT or not, your "working" timezone will be UTC).
You could make use of
1) date_default_timezone_set - Sets the default timezone used by all date/time functions in a script
2) Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.
The important thing to keep in mind is not UTC, but that all times stored must be standardized to one timezone. So, if your PHP server and your database server both use the same timezone, the only issue that arises is when you need to display a location-aware time to the user or when you allow a user to enter a datetime from another timezone.
PHP has a nice, though somewhat scantly documented class, called DateTime. And some ancillary classes like DateTimeZone, DateInterval, etc. These make converting from db time to user time pretty simple.
So does anyone have any suggestions for the best way on how I can make this application timezone aware considering the server isn't set to UTC?
If you manage to come with any scheme for remapping the timezones its going to be horribly complicated and even more impossible to ever fix properly. Do yourself a favour and get the server timezone to UTC and fix your existing data.
First of allyou have to convert the date time selected by user to timestamp.
You have to use Server time zone offset and save the time to server in GMT.
This is the best way because while displaying the date just add the offset of the user
and convert and show.
I have implemented this for my client as it was an auction site and user may add item from AUS in his time and bidder will be from US. Time zone issues was there and we implemented after a lots of rerence.
You know one thing best and easy way is , do like ebay . just save the user time zone and show time with the time zone. No conversion nothing. Simple and better . 10:35 EST :)
If you wannabe perfect in time zone conversion, think about daylight saving time also. start date and end date on each year will change slightly. If you want to be accurate you have to save the daylight starting and ending date in db and add that difference too .:)
For working with datetime in different timezones and formats you can try to use PHP library Dater (https://github.com/barbushin/dater). Cheers!
I have a social network site I have been working on for a couple years in PHP/MySQL, I am now re-buidling the whole site from scratch again though. This time around I would really like to add in the ability for users to set a timezone for times on my site.
So with that said, I am asking on a guide from start to finish of the steps I need to include to do this please. My old site used mysql datetime for all dates and times and it worked great but I read that it is best to use like a text filed and store all dates and times with UTC, can someone explain how I could do this? Would I still be able to use the now() function in php to save a time to the mysql?
Also I have seen the list that php can generate of all the timezones, the one where it shows like a million (not really) but I am wondering, would it be possible to show some sort of map with images or something and link to the main timezones?
Please any tips for setting a users timezone, I can do that part, but once I have a user's timezone saved and ready to use, how can I make sure the users see's the correct time and how do I save times in the correct time.
Sorry if this was confusing, any help would be great though, thanks.
When working with php, from my experience, it is the best to store timestamps, generated with time(), as an int in the database. While it may not be that easy to read them when looking at the database (as you cannot guess the actual date just from the number), but the timestamp is the most-native thing when working with dates in php.
To save each user's timezone, you can simply save the offset, in either hours, or better (as some timezones are half an hour off) in minutes. So for example my timezone offset would be +60 (UTC+1), while in America most will have something like -480 (UTC-8) or similar.
Then when displaying the times for a user, you just pick the timestamp (which is in UTC time) and the timezone offset and generate a readable date from it using the standard date() function for formatting.
For example:
<?php
$time = time(); // from database or time() for "now"
$offset = -480; // from database
// add the offset to the time you want to display and you have the user's time
echo date( 'd.m.Y H:i', $time + $offset * 60 );
?>
In addition you could then also store the formatting string (d.m.Y H:i) in the database, so that every user can pick his favorite format.
This topic gets complicated especially when you factor in daylight savings and the fact that your server will be in a different time zone from some of your members.
I suggest you take a look at some libraries out there that have been built to handle these issues. The PEAR package Date might be a good place to start. http://pear.php.net/package/Date
Basically, you would want your members to select a timezone for their profile. Then convert all times to UTC (to remove the offset of the server location) and store them in your database as a timestamp. When displaying the times, apply the timezone offset the member chose for themself (maybe with UTC as the default) as well as a date display format.