PHP Datetime with MySQL datetime - php

I want to ask about changing a datetime value of PHP with datetime value from MySQL data.
I have try to do this at PHP:
$sitgl = date('Y-m-d', strtotime(2012-01-12));
$sijam = date('H:i:s', strtotime(13:00:00));
$awal = $sitgl.' '.$sijam;
$awal2 = date('Y-m-d H:i:s', strtotime($awal));
$debrangkat = strtotime($awal2);
And I'm trying to convert same datetime at MySQL like this (convert it to seconds):
SELECT date_start_book, time_start_book, (TO_DAYS(CAST(date_start_book AS DATE))*86400) + TIME_TO_SEC(CAST(time_start_book AS TIME)) FROM `t_request_queue` WHERE `request_id` = '1301-0087'
which is date_start_book value is 2012-01-12 and time_start_book value is 13:00:00
My question is: why the PHP code return value : 1357970400 but the MySQL value return 63525214800 ?
what must I do to make both of value is same? Is strtotime() not return a seconds or why?

First of all as others have suggested that php code is really hurting brain. You could make that Unix Timestamp in just one line. But to answer your real question. MYSQL TO_DAYS works different than PHP UNIX Timestamp
According to MySQL Website
Given a date date, returns a day number (the number of days since year 0).
mysql> SELECT TO_DAYS(950501);
-> 728779
mysql> SELECT TO_DAYS('2007-10-07');
-> 733321
TO_DAYS() is not intended for use with values that precede the advent of the Gregorian calendar (1582), because it does not take into account the days that were lost when the calendar was changed. For dates before 1582 (and possibly a later year in other locales), results from this function are not reliable
And according to PHP Website timestamp is
Returns the current time measured in the number of seconds since the
Unix Epoch (January 1 1970 00:00:00 GMT).
And hence the difference in two values. Their starting point is way too distant from each other. MySQL starts from year 0 and PHP starts from year 1970.
Suggestion
I would suggest you save php's timestamp in mysql rather than a formatted date time. This will help you stay consistent and allow you to perform any date or time comparisons easily.

Finally, I change the PHP to datetime and at query I'm using ADD_DAYS to add a date with a seconds then I compare it with the PHP datetime result.
So many thanks to all contributor.

Related

Select date stored as Unix Timestamp and compare with given Unix TimeStamp

I am stuck for couple of Days on SQL specific scenario. The scenario is as follows,
I have a table, lets call it traffic which has 2 columns -> date and `vehicle (well many more but those are the two I need to match).
The date column is stored as Unix Timestamp. Now this would have been easy to just compare the current date (obtain from php from time() function) however the trick here is that some of these dates have time attached to them also.
For example if you run strtotime(13-02-2017 13:00) and strtotime(13-02-2017) you will get 2 different results. Basically I only care to match the date and not the time.
So I need some way to select the vehicle and date from the database that are equalled to the current Unix Timestamp but with the trick explained above, so I just need to much the date ONLY if possible.
You can use FROM_UNIXTIME() to convert a timestamp to a datetime, and then use the DATE() function to get the date part of that.
WHERE DATE(FROM_UNIXTIME(date)) = CURDATE()
However, this can't use an index, so another way that can make use of an index is to check if it's in a range of timestamps for the current date:
WHERE date BETWEEN UNIX_TIMESTAMP(CURDATE()) AND UNIX_TIMESTAMP(CURDATE()) + 86399
(there are 86400 seconds in a day).
SELECT * FROM traffic WHERE DATE(date) = DATE(CURRENT_TIMESTAMP);

Changing date format globally

I am using PHP and mysql and using either Date or DateTime to save dates in mysql database. On site I have been displaying dates the way they are saved in database.
But now I want to show dates EVERYWHERE on site using one format:
April 17 2013
or
April 17 2013 12:20:50
I know I can use date and strtotime functions to display dates in above format. However there are a lot of places where I have date displaying code. So I am looking to automate the process where my current code works and displays dates in above format.
Any idea of how mysql trigger or some php magic could be created that converts all dates run through SELECT query automatically without changing my sql or php code since I have a lot of places in my code and it would be overkill to change code at all places?
For Example:
Date Saved in DB: 2013-04-16 12:41:26
SELECT QUERY: SELECT * FROM myTable
PHP: echo $row->dated; displays 2013-04-16 12:41:26
I want that without changing my php code, dates should be shown in above mentioned format globally on whole site.
Any ideas please how it could be achieved ?
You can directly format in via query using DATE_FORMAT()
SELECT DATE_FORMAT(myDate, '%M %d %Y %h:%i') myDate
FROM TableName
SQLFiddle Demo
and echo in your PHP: $row->myDate
MySQL Trigger doesn't project values and It is only fired during CrUD operations.
I would like to suggest you an alternative approach which i love to use.
You should use the epoch time. An epoch time is basicly the number of second that has passed since 1 January 1970
One if the benefits i love is that it is very easy to calculate
differences in time since you are just dealing with number of
seconds and not a complicated format such as sec min hrs
Another benefit is that it is very easy to store since its a
integer so you can store it in a sql db and have your php code understand it without worrying about the format and things like that.
In php, if you use the time() function, it will return the epoch time.
And if you ever want to display it in a user friendly way. you can use the following code:
$epoch = time();
$dt = new DateTime("$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2012-08-15 00:00:00
As you can see, the format of the date is very flexible and thus easy to use.
A nice example to find the date 1 week ago:
$epoch = time() - 604800; //604800 seconds = 7 days
$dt = new DateTime("$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2012-08-15 00:00:00

PHP -Comparing Unix Timestamp To Now

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).

How to calulate the difference between a MySQL timestamp and the current time in PHP

I'm trying to calculate the difference between a timestamp retrieved from a MySQL database and the current time.
Appreciate the help.
As mentioned by #RemoteSojourner, I got the current time in a UNIX timestamp format (which returns time in seconds), I got the timestamp from the DB (using an ORM) and converted that to a UNIX timstamp too and then subtracted the two timestamps.
$current_time = strtotime("now");
$last_access_time = strtotime($this->last_access);
$inactivity_duration = $current_time - $last_access_time;
This example makes the difference between now and one hour ago.
select timediff(now(), now() - interval 1 hour)
You can use the strtotime function to parse the MySQL timestamp into a Unix timestamp can be further parsed or formatted in the PHP date function.
Retrieve the datetime from mysql like this
SELECT UNIX_TIMESTAMP(`time_col`) FROM `tablename`...
AND compare it to time()

What's the difference between PHP time and SQL time?

Why is the timestamp generated by the PHP time() function so different from SQL datetime?
If I do a date('Y-m-d', time()); in PHP, it gives me the time now, as it should. If I just take the time() portion and do:
$now = time();
//then execute this statement 'SELECT * FROM `reservation` WHERE created_at < $now'
I get nothing. But hey, so if the value of $now was 1273959833 and I queried
'SELECT * FROM `reservation` WHERE created_at < 127395983300000000'
then I see the records that I have created. I think one is tracked in microseconds vs the other is in seconds, but I can't find any documentation on this! What would be the right conversion between these two?
The time() function doesn't return microseconds, so it should work if you're using the correct datatype. But you have 2 different datatypes right now, INT and a date field (could be DATE/DATETIME/TIMESTAMP). If you want to compare a date in the database to a timestamp as integer, you could use something like:
SELECT * FROM Tbl WHERE UNIX_TIMESTAMP(date) < $timestamp;
time() gives a Unix timestamp (seconds passed since 01-01-1970) - SQL wants to have timestamps in format YYYY-mm-dd hh-ii-ss which is done by date() - so if you don't want to call 2 PHP functions, just use $now = date("Y-m-d H:i:s") or, better, change your SQL query to created_at < NOW().
They're just 2 different ways of storing dates, each with their advantages and disadvantages. You can use MySQL's date field, or simply store unix timestamps in an INT field. You can also use:
SELECT UNIX_TIMESTAMP(field_name) FROM ...
to return a date field as a Unix timestamp.
The MySQL date field is human-readable and can store any date in the foreseeable future. However, it does not store timezone information which can cause serious issues if not handled correctly. Facebook had this problem a while back.
Unix timestamps store timezone information (since it's defined as the number of seconds since 12:00am January 1st 1970 UTC). Comparison operations are faster on integers, and PHP's time/date functions are designed to be used with Unix timestamps. However, Linux can only support dates from 1902 to 2038 and on Windows from 1970 to 2038. MySQL and architecture in general will switch to 64-bit integers long before 2038 arrives, but if you need to store dates that are in the distant future or past, Unix time isn't for you.

Categories