I have the following problem. I am trying to compare two datetime values in PHP but the calculation is invalid. There is about 8 hours of difference. I am on my development machine using WAMPServer
if(strtotime($date_time_from_db) < time())
{
// do something
}
The datetime value in the database is in the following format: Y-m-d H:i:s. How can I do this accurately? Also, is using time() a good idea? What happens if the user changes the time on their machine?
Thanks very much!
Don't do date/time comparisons in PHP if you're pulling those values from a database. That involves a double round-trip of conversions: date/time -> text -> date-time. You can do the exact same thing at the database level:
SELECT ...
FROM table
WHERE datetimefield < now()
which allows use of indexes (good) and eliminates two type conversions (also good).
As for user changing time - well, that's just the user's machine. Unless you're doing this as part of an app for sale, then the user has absolutely no way of affecting the time on your database server.
Related
I am new in php and I saw some programmer store datetime in database by php date() or mysql NOW() or take column as timestamp. I want to know that the difference between these three is and also how to convert these three formats to users local time worldwide.
As per the mysql's law you can have only one timestamp field,no
restrictions for having number of datetime field..
You can set the
timestamp field for onupdate current timestamp or current
timestamp..And these field type not affecting the date insert
method..
If you are using date() function you can set your own
date format..But not in the now()
For date format the syntax check this article https://www.w3schools.com/php/func_date_date.asp
Finaly Datetime and timestampis mysql
date() and NOW()is php
There's a few things to consider:
TIMESTAMP columns are limited to dates between 1931 and 2038, as they're 32-bit timestamp values.
DATETIME columns can go up to the year 9999. While they don't auto-populate like TIMESTAMP values do by default, they're less restricted, you can have as many as you want per table.
When inserting times your PHP clock and your database clock might differ slightly. Using NTP can help narrow that gap, but drifts do happen. PHP's date() function requires formatting into ISO-8601 format for inserting (YYYY-MM-DD HH:MM:SS). The MySQL NOW() function does not, same with UTC_TIMESTAMP().
I strongly recommend using UTC time in your database for a few reasons:
If you store in local time you'll need to store the time-zone as well, and those can change in wild and bizarre ways.
You may need to accommodate other time zones in the future, which means you might have multiple local times in your data where each record might have a different meaning from others.
Your server might get moved between time-zones which can shift all your data.
So store with UTC and render out as local times based on the user's time-zone preference or some sensible default for your application. Remember, time formatting is often a fussy thing, every country has different date formatting standards, and even a single country might have multiple preferences for long-form, short-form, or numerical forms.
I have this table
Name Birth_Date Register_Date
---------------------------------------------------------------
Ali 1990-03-22 2010-03-1 15:1:42
Ali1 1991-07-18 2010-03-2 12:44:2
When I inserted these values, I inserted the Birth_Date as a String such as '1990-03-22', and I used 'NOW()' for Register_Date.
NOW() will generate the current datetime according to the MySql Server.
Now when I try to get the time between the current date and the Register_Date (Time passed since he registered), I use the following:
SELECT YEAR(CURDATE())-YEAR(register_date) ...
In PHP, if I wanted to do that, I suppose I have to get the current date: date('Y-m-d H:i:s');
My question is, is there a difference between calculating the date difference (between a date and today) via MySql or via PHP?
Currently, on my localhost (XAMPP), CURDATE() and date(..) generates the same date, but will it generate the same date for other users when my website goes online?
If both your mysql and PHP server are operating on the same timezone and have their clocks properly synchronized, you wont have an issue.
if you want to upload your php website and your DB on the same server I think you'll not have problem , but If you use different servers you may have time issues.
to avoid this issue I advice you to save the time with time zone, to be able to get the correct time from any server.
The question i guess is kind of 2 questions:
How do i even GET the current time in php and in a format that is easily compared to and
Once i have that, i have a mysql timestamp in this format, 2011-06-30 04:33:00 , that I need to be compared to the php current time.
thank you so so much in advance,
Binny
I'm assuming you're storing it as a DATETIME column. As such, in MySQL
SELECT
UNIX_TIMESTAMP(`date_column`) AS `timestamp`,
...
FROM
...
Then, in PHP:
$time_diff_in_seconds = time() - $query_result['timestamp']
However, I'd just let the database do it:
SELECT
TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, `date_column`)) AS time_diff,
...
FROM
...
strtotime($query_result['timestamp'])
This will convert your MySQL timestamp value to the correct seconds since Jan 1, 1970 value. Then it's just a matter of subtracting the two to get the difference.
One thing you should check: are the two times coming from the same machine? If they are coming from different machines, you should worry about time zones and synchronization.
I'm struggling here a bit with the time zone in MySQL.
What I need to do is to compare two time values in the database - both with different time zone to see if the specific event has already happened. I would like to do it inside of the sql statement - any idea if it's possible - and if so - if you could provide an example of the sql statement please.
Don't store dates and times for a particular timezone. Store the dates/times in UTC, compare those, and then convert the result (if there is one) to the timezone you would like to display it in.
The examples for DateTime::setTimeZone() should point you in the right direction for doing conversions.
http://www.php.net/manual/en/datetime.settimezone.php
See more about UTC: http://en.wikipedia.org/wiki/UTC
I have built a small forum where users can post messages. My server is in the United States, but the userbase for the forum is in Taiwan (+15hrs).
When someone posts to the form, I store the time in my mySQL database in the format YYYY-MM-DD HH:MM:SS. When I look in the database, the time displays the proper time (the time that the person in Taiwan posted it).
However, when I use UNIX_TIMESTAMP to get the date out of the database, the time is altered.
Example:
I post something to the forum. The datetime on my wrist watch is 2009-10-2 11:24am (Taiwan Time)
I look in the database and it says the datetime is 2009-10-2 11:24am (same time as my wrist watch. good!)
Then when I use UNIX_TIMESTAMP to display the date on my website, it shows as 2009-10-03 4:22 pm (bad! it applied an offset)
Is there a way I can get UNIX_TIMESTAMP to stop converting the time (applying an offset) when I query the date from the database?
Extra Info:
I'm using PHP
I have set the timezone in my PHP to Taiwan (date.timezone = Asia/Taipei)
If a user is in another timezone than Taiwan, I want it to convert the time to Taipei time. The site is nearly 100% Taiwan used so I just want Taiwan time to show all the time even if they're in another timezone.
I display the date in lots of areas around the site in different date() formats.
Basically everything works great except that when I use UNIX_TIMESTAMP to query the data out, it applies an offset to the time.
Thanks!
MySQL writes dates "as-is", also reads them so, but UNIX_TIMESTAMP treats any input dates as in your local timezone and converts them to UTC/GMT timestamps meaning it will apply your local timezone offset, now if you process your timestamps returned from mysql via eg. php date() it will again apply your local timezone offset(note there is also gmtime() which does not do that), which will produce unwanted results.
But you can get by with this following trick which will subtract your session timezone before UNIX_TIMESTAMP() applies it, so you will get the exact number regardless of the server/local timezone if you want the exact same date in db as if it were a GMT time.
mysql> SELECT UNIX_TIMESTAMP(CONVERT_TZ("2013-05-27","GMT",##session.time_zone));
+--------------------------------------------------------------------+
| UNIX_TIMESTAMP(CONVERT_TZ("2013-05-27","GMT",##session.time_zone)) |
+--------------------------------------------------------------------+
| 1369612800 |
+--------------------------------------------------------------------+
1 row in set (0.00 sec)
Another solution would be to set the servers or session timezone to 0(GMT), so there will be no real conversions taking place.
MySQL takes system's default timezone setting unless told otherwise, it explains the problems you are having; take a look at MySQL's time zone reference manual for more details. Based on my past experience I've come to a conclusion UTC is the best choice for storing date and time; when displaying it to the user, they are converted to user's timezone.
If possible, change all date and time entries in the DB to UTC, configure timezone in PHP usingdate_default_timezone_set()and make sure to convert it properly when rendering it to the user and when storing it in the database as well. If storing UTC values is not an option, you may simply convert them by following time zone reference guide the same way as with UTC.
What you need to do is grab raw date and time from the database and then use PHP's DateTime to convert it. Take a look at DateTimeZone as well.
The best that I have found to this problem is using this:
SELECT UNIX_TIMESTAMP(CONVERT_TZ(<<>>,'+15:00','+00:00')) +TIMESTAMPDIFF(second,utc_timestamp(), now())
Example: I want to get the timestamp of 31-may-2012 at 23:59:59, Local time.
SELECT UNIX_TIMESTAMP(CONVERT_TZ('2012-05-31 23:59:59','+15:00','+00:00')) +TIMESTAMPDIFF(second,utc_timestamp(), now())
This way I get the timestamp GMT-0, corresponding to the localtime.
I have found a possible solution which is to just retrieve the date from the database without converting it to Unix time, and then just using strtotime(); to convert it to Unix time. Basically instead of converting using sql, i'm converting using php. The only things I don't like about it are: strtotime() < I'm not sure how reliable this function is, and I have to go and change about 100 places where i'm using UNIX_TIMESTAMP (doh!)
Are there any other ways?