I have two DateTime, one in database in the same php DateTime format: Y-m-d H:i:s. One is stored in a database and one is retreived.
Unfortunately the second one cannont be compared exactly becazuse there is a certain time (hours) difference. It should be exactly the same time but the difference makes it hard to do a DateTime comparison knowing that comparition must be precise closer to now because of the publish/update date is a matter of a short time (hours, minutes, seconds).
Example: database: 1999-09-06 07:00:00, retrieved: 1999-09-06 09:00:00
I stored the datetime from the distant website a while ago. It worked a few months ago but when I tried to do the same thing today, it failed.
Looks like the webserver has a different timezone as your local time. You can set the TimeZone for the DateTime Class manually. http://php.net/manual/de/datetime.settimezone.php
If the time difference is always the same, you can simple change one value before comparing it. In PHP you can do that quite easily with the strtotime() by subtracting 2 hours. The same can be done in MySQL (or any other DB system) by using SELECT date_column + INTERVAL 2 HOUR: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add
Related
All,
I'm trying to decide how to deal with time in a project which relies on (server) time intervals (in short, some content is available after user completed a specific action at least n hours before). Right now, it seems like the easiest option would be to extract the Unix time stamp with time() and store it as is in MySQL.
Any reason why this is not a good idea? Any gotcha I need to be aware of? Performance impact?
Timestamps are fine. Don't divide them, it's unneeded calculation. If you plan to query (per object) about a timeout more often than update it then you would be better off storing the expiration time instead of the current (so calculating delta only once). Beware about DATETIME columns: they don't regard timezone setting, while your PHP does... so if you happen to have different timezone settings on different requests, then you're out of luck. Timestamps are absolute, and they also account for manace like daylight-savings times, where 3:01 is 2 minutes after 1:59...
Seems fine to me. Though you should probably store it as a DATETIME and use DateTime objects, rather than UNIX timestamps and time().
$time = new DateTime;
echo $time->format("Y-m-d H:i:s"); //Outputs current time, example: 2012-10-13 22:58:34
Actually, this is the best idea. The function time() give you the number of seconds from January 1th, 1970 00:00:00. There's no performance impact because it's only an integer. In MySQL, create a field like that INT, 10, Unsigned.
Time will give you performance on the SELECT and the WHERE. See http://gpshumano.blogs.dri.pt/2009/07/06/mysql-datetime-vs-timestamp-vs-int-performance-and-benchmarking-with-myisam/
The only problem you have is : time is limited to year 2038... but by the time 2038 come, the internal computer clock bytes will be larger ... hope so.
The other thing you may want to worrie about the DATETIME is : PHP time() run under UTC, while DATETIME depend on the timezone...
Stats when you do INSERT with 10000000 rows.
Stats when you SELECT / WHERE with indexes :
For a while I had been using a raw MySQL NOW() function to record the time/date in my MySQL DB until I realized the host's timezone variable was three hours ahead of PST. I've fixed this using DATE_SUB(NOW(), INTERVAL 3 HOUR), but now I have a ton of timestamps that are three hours ahead, and all future timestamps that are the showing the correct time.
Is there a PHP function to evaluate timestamps recorded before I made the fix so I can offset them when they display in my admin utility?
For example:
if($timestamp < 2012-02-16 21:57:18) {
$timestamp - 3 hours;
}
New Timestamp (offset by 3 hours behind)
$timestamp = date('Y-m-d H:i:s',strtotime($row['timestamp_column_name'])-(3*60*60));
Create a second column in your table (perhaps?) and store the offset time - perhaps call it the admin time OR store the admin time offset from the system's time OR you can set the timezone PHP should use using something like the options mentioned here: PHP timezone not set .
the magical function strtotime does all the work for you. seriously check it out for adding, manipulating and even reading human readable forms of dates. Then the date function is good for formatting it back into any form.
For many input formats, strtotime is the way to go. However, its heuristical approach may lead to surprising results, so if you only want to parse a specific format, use strptime.
I'm retrieving a unix timestamp from a DB and I want to check if this datetime has passed already.
I tried using an if statement to compare to time() but it always says the time has passed already.
What am I doing wrong?
EDIT: Just some more info..to determine am/pm I'm adding 12 to the hour if its PM before running it through mktime(). (Is this right?)
It's stored in the DB as int not as any datetime types.
Your PHP time could be affected by PHP's timezone. Use date_default_timezone_get() to find out what time zone you're in.
Make sure the timezones in the DB and PHP are the same, use NOW() function to fill the DB column with current timestamp (the column should be of datetime type), then you can get the timestamp using UNIX_TIMESTAMP() MySQL function which compares against PHP's time() just nice.
Alternatively, you can fill the DB column with something like
mysql_query("INSERT INTO your_table (your_date) VALUES (FROM_UNIXTIME(" . time() . "))")
That should work even with timezone discrepancies.
If you are using mktime to create a UNIX timestamp, PHP is using the timezone settings to interpret what you mean by the given parameters. It's possible that you should be using gmmktime. It depends on how the timestamps in the database are being created; I cannot say for sure without seeing more code and having a more detailed explanation.
I generally prefer to simply store all dates as DATETIME types in the UTC (GMT) timezone. It tends to be less confusing.
Just some more info..to determine am/pm I'm adding 12 to the hour if its PM before running it through mktime(). (Is this right?)
12 PM is hour 12.
1 PM is hour 13.
So you don't always add 12. (i.e., 12 Noon is the exception).
This question already has answers here:
Should I use the datetime or timestamp data type in MySQL?
(40 answers)
Closed 9 years ago.
Probably many coders want to ask this question. it is What's the adventages of each one of those MySQL time formats. and which one you will prefer to use it in your apps.
For me i use Unix timestamp because maybe i find it easy to convert & order records with it, and also because i never tried the DATETIME thing. but anyways i'm ready to change my mind if anyone tells me i'm wrong.
Thanks
Timestamp (both PHP ones and MySQL's ones) are stored using 32 bits (i.e. 4 bytes) integers ; which means they are limited to a date range that goes from 1970 to 2038.
DATETIME don't have that limitation -- but are stored using more bytes (8 bytes, if I'm not mistaken)
After, between storing timestamps as seen by PHP, or timestamps as seen by MySQL :
using PHP timestamps means manipulations are easier from PHP -- see Date/Time Functions
using MySQL's timestamps means manipulations are easier from MySQL -- see 11.6. Date and Time Functions
And, for more informations between MySQL's TIMESTAMP and DATETIME datatypes, see 10.3.1. The DATETIME, DATE, and TIMESTAMP Types
As others have said, timestamps can represent a smaller range of datetimes (from 1970 to 2038). However, timestamps measure the number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC), thereby making them independent of time zone, whereas DATETIME stores a date and time without a time zone. In other words, timestamps unambiguously reference a particular point in time, whereas the exact point in time a DATETIME refers to requires a time zone (which is not stored in a DATETIME field). To see why this can matter, consider what happens if we change our time zone.
Let's say we want to store the datetime 2010-03-27 12:00 UTC. If we store this and retrieve it using a timestamp or DATETIME, then there usually appears to be no difference. However, if the server now changes so that the local time zone is UTC+01, then we get two different results if we pull out the datetime.
If we'd set the field to a DATETIME, it would report the datetime as 2010-03-27 12:00, despite the change in time zone. If we'd set the field to a timestamp, the date would be reported as 2010-03-27 11:00. This isn't a problem with either datatype -- it's just a result of the fact that they store slightly different information.
That really depends. I'll give you 2 examples where one overcome the other:
Timestamp is better than DATETIME when you want to store users session in the database and the session creation time (in Timestamp format) is used for fast row retrieval (with index).
E.g. table may look like this:
[session_create_time AS Timestamp][IP_address AS 32bit Int][etc...]
Having an index on the first two columns can really speed up your queries. If you had a DATETIME value type for the session_create_time field, then it could be taken much more time. Take into account that session queries are executed each time a user request a page, so efficiency is crucial.
DATETIME is better than Timestamp when you want to store a user's date of birth or some historic events that require flexible time range.
Unless digitizing records prior to January 1, 1970, I like the UNIX epoch. Its just a matter of preference, whole unsigned numbers are simpler to deal with when using multiple languages.
Just keep in mind, the epoch starts at January 1, 1970. A lot of companies had been in business for decades, if not longer, prior to that.
I'm using the America/New York timezone. In the Fall we "fall back" an hour -- effectively "gaining" one hour at 2am. At the transition point the following happens:
it's 01:59:00 -04:00
then 1 minute later it becomes:
01:00:00 -05:00
So if you simply say "1:30am" it's ambiguous as to whether or not you're referring to the first time 1:30 rolls around or the second. I'm trying to save scheduling data to a MySQL database and can't determine how to save the times properly.
Here's the problem:
"2009-11-01 00:30:00" is stored internally as 2009-11-01 00:30:00 -04:00
"2009-11-01 01:30:00" is stored internally as 2009-11-01 01:30:00 -05:00
This is fine and fairly expected. But how do I save anything to 01:30:00 -04:00? The documentation does not show any support for specifying the offset and, accordingly, when I've tried specifying the offset it's been duly ignored.
The only solutions I've thought of involve setting the server to a timezone that doesn't use daylight savings time and doing the necessary transformations in my scripts (I'm using PHP for this). But that doesn't seem like it should be necessary.
Many thanks for any suggestions.
I've got it figured out for my purposes. I'll summarize what I learned (sorry, these notes are verbose; they're as much for my future referral as anything else).
Contrary to what I said in one of my previous comments, DATETIME and TIMESTAMP fields do behave differently. TIMESTAMP fields (as the docs indicate) take whatever you send them in "YYYY-MM-DD hh:mm:ss" format and convert it from your current timezone to UTC time. The reverse happens transparently whenever you retrieve the data. DATETIME fields do not make this conversion. They take whatever you send them and just store it directly.
Neither the DATETIME nor the TIMESTAMP field types can accurately store data in a timezone that observes DST. If you store "2009-11-01 01:30:00" the fields have no way to distinguish which version of 1:30am you wanted -- the -04:00 or -05:00 version.
Ok, so we must store our data in a non DST timezone (such as UTC). TIMESTAMP fields are unable to handle this data accurately for reasons I'll explain: if your system is set to a DST timezone then what you put into TIMESTAMP may not be what you get back out. Even if you send it data that you've already converted to UTC, it will still assume the data's in your local timezone and do yet another conversion to UTC. This TIMESTAMP-enforced local-to-UTC-back-to-local roundtrip is lossy when your local timezone observes DST (since "2009-11-01 01:30:00" maps to 2 different possible times).
With DATETIME you can store your data in any timezone you want and be confident that you'll get back whatever you send it (you don't get forced into the lossy roundtrip conversions that TIMESTAMP fields foist on you). So the solution is to use a DATETIME field and before saving to the field convert from your system time zone into whatever non-DST zone you want to save it in (I think UTC is probably the best option). This allows you to build the conversion logic into your scripting language so that you can explicitly save the UTC equivalent of "2009-11-01 01:30:00 -04:00" or ""2009-11-01 01:30:00 -05:00".
Another important thing to note is that MySQL's date/time math functions don't work properly around DST boundaries if you store your dates in a DST TZ. So all the more reason to save in UTC.
In a nutshell I now do this:
When retrieving the data from the database:
Explicitly interpret the data from the database as UTC outside of MySQL in order to get an accurate Unix timestamp. I use PHP's strtotime() function or its DateTime class for this. It can not be reliably done inside of MySQL using MySQL's CONVERT_TZ() or UNIX_TIMESTAMP() functions because CONVERT_TZ will only output a 'YYYY-MM-DD hh:mm:ss' value which suffers from ambiguity problems, and UNIX_TIMESTAMP() assumes its input is in the system timezone, not the timezone the data was ACTUALLY stored in (UTC).
When storing the data to the database:
Convert your date to the precise UTC time that you desire outside of MySQL. For example: with PHP's DateTime class you can specify "2009-11-01 1:30:00 EST" distinctly from "2009-11-01 1:30:00 EDT", then convert it to UTC and save the correct UTC time to your DATETIME field.
Phew. Thanks so much for everyone's input and help. Hopefully this saves someone else some headaches down the road.
BTW, I am seeing this on MySQL 5.0.22 and 5.0.27
MySQL's date types are, frankly, broken and cannot store all times correctly unless your system is set to a constant offset timezone, like UTC or GMT-5. (I'm using MySQL 5.0.45)
This is because you can't store any time during the hour before Daylight Saving Time ends. No matter how you input dates, every date function will treat these times as if they are during the hour after the switch.
My system's timezone is America/New_York. Let's try storing 1257051600 (Sun, 01 Nov 2009 06:00:00 +0100).
Here's using the proprietary INTERVAL syntax:
SELECT UNIX_TIMESTAMP('2009-11-01 00:00:00' + INTERVAL 3599 SECOND); # 1257051599
SELECT UNIX_TIMESTAMP('2009-11-01 00:00:00' + INTERVAL 3600 SECOND); # 1257055200
SELECT UNIX_TIMESTAMP('2009-11-01 01:00:00' - INTERVAL 1 SECOND); # 1257051599
SELECT UNIX_TIMESTAMP('2009-11-01 01:00:00' - INTERVAL 0 SECOND); # 1257055200
Even FROM_UNIXTIME() won't return the accurate time.
SELECT UNIX_TIMESTAMP(FROM_UNIXTIME(1257051599)); # 1257051599
SELECT UNIX_TIMESTAMP(FROM_UNIXTIME(1257051600)); # 1257055200
Oddly enough, DATETIME will still store and return (in string form only!) times within the "lost" hour when DST starts (e.g. 2009-03-08 02:59:59). But using these dates in any MySQL function is risky:
SELECT UNIX_TIMESTAMP('2009-03-08 01:59:59'); # 1236495599
SELECT UNIX_TIMESTAMP('2009-03-08 02:00:00'); # 1236495600
# ...
SELECT UNIX_TIMESTAMP('2009-03-08 02:59:59'); # 1236495600
SELECT UNIX_TIMESTAMP('2009-03-08 03:00:00'); # 1236495600
The takeaway: If you need to store and retrieve every time in the year, you have a few undesirable options:
Set system timezone to GMT + some constant offset. E.g. UTC
Store dates as INTs (as Aaron discovered, TIMESTAMP isn't even reliable)
Pretend the DATETIME type has some constant offset timezone. E.g. If you're in America/New_York, convert your date to GMT-5 outside of MySQL, then store as a DATETIME (this turns out to be essential: see Aaron's answer). Then you must take great care using MySQL's date/time functions, because some assume your values are of the system timezone, others (esp. time arithmetic functions) are "timezone agnostic" (they may behave as if the times are UTC).
Aaron and I suspect that auto-generating TIMESTAMP columns are also broken. Both 2009-11-01 01:30 -0400 and 2009-11-01 01:30 -0500 will be stored as the ambiguous 2009-11-01 01:30.
I think micahwittman's link has the best practical solution to these MySQL limitations: Set the session timezone to UTC when you connect:
SET SESSION time_zone = '+0:00'
Then you just send it Unix timestamps and everything should be fine.
But how do I save anything to 01:30:00
-04:00?
You can convert to UTC like:
SELECT CONVERT_TZ('2009-11-29 01:30:00','-04:00','+00:00');
Even better, save the dates as a TIMESTAMP field. That's always stored in UTC, and UTC doesn't know about summer/winter time.
You can convert from UTC to localtime using CONVERT_TZ:
SELECT CONVERT_TZ(UTC_TIMESTAMP(),'+00:00','SYSTEM');
Where '+00:00' is UTC, the from timezone , and 'SYSTEM' is the local timezone of the OS where MySQL runs.
Mysql inherently solves this problem using time_zone_name table from mysql db.
Use CONVERT_TZ while CRUD to update the datetime without worrying about daylight savings time.
SELECT
CONVERT_TZ('2019-04-01 00:00:00','Europe/London','UTC') AS time1,
CONVERT_TZ('2019-03-01 00:00:00','Europe/London','UTC') AS time2;
This thread made me freak since we use TIMESTAMP columns with On UPDATE CURRENT_TIMESTAMP (ie: recordTimestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) to track changed records and ETL to a datawarehouse.
In case someone wonder, in this case, TIMESTAMP behave correctly and you can differentiate between the two similar dates by converting the TIMESTAMP to unix timestamp:
select TestFact.*, UNIX_TIMESTAMP(recordTimestamp) from TestFact;
id recordTimestamp UNIX_TIMESTAMP(recordTimestamp)
1 2012-11-04 01:00:10.0 1352005210
2 2012-11-04 01:00:10.0 1352008810
I was working on logging counts of visits of pages and displaying the counts in graph (using Flot jQuery plugin). I filled the table with test data and everything looked fine, but I noticed that at the end of the graph the points were one day off according to labels on x-axis. After examination I noticed that the view count for day 2015-10-25 was retrieved twice from the database and passed to Flot, so every day after this date was moved by one day to right.
After looking for a bug in my code for a while I realized that this date is when the DST takes place. Then I came to this SO page...
...but the suggested solutions was an overkill for what I needed or they had other disadvantages. I am not very worried about not being able to distinguish between ambiguous timestamps. I just need to count and display records per days.
First, I retrieve the date range:
SELECT
DATE(MIN(created_timestamp)) AS min_date,
DATE(MAX(created_timestamp)) AS max_date
FROM page_display_log
WHERE item_id = :item_id
Then, in a for loop, starting with min_date, ending with max_date, by step of one day (60*60*24), I'm retrieving the counts:
for( $day = $min_date_timestamp; $day <= $max_date_timestamp; $day += 60 * 60 * 24 ) {
$query = "
SELECT COUNT(*) AS count_per_day
FROM page_display_log
WHERE
item_id = :item_id AND
(
created_timestamp BETWEEN
'" . date( "Y-m-d 00:00:00", $day ) . "' AND
'" . date( "Y-m-d 23:59:59", $day ) . "'
)
";
//execute query and do stuff with the result
}
My final and quick solution to my problem was this:
$min_date_timestamp += 60 * 60 * 2; // To avoid DST problems
for( $day = $min_date_timestamp; $day <= $max_da.....
So I am not staring the loop in the beginning of the day, but two hours later. The day is still the same, and I am still retrieving correct counts, since I explicitly ask the database for records between 00:00:00 and 23:59:59 of the day, regardless of the actual time of the timestamp. And when the time jumps by one hour, I am still in the correct day.
Note: I know this is 5 year old thread, and I know this is not an answer to OPs question, but it might help people like me who encountered this page looking for solution to the problem I described.