This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php date compare
I have a date that I take from the mySQL database that looks like this:
2011-06-20
And I get the date of the current day in this way:
$todaydate = date('Y-m-d');
What I need to know is how do I compare the two results?
How can I compare the dates and understand for example if a week is passed from the database date or a month or a year..etc..?
Thank you!!
There is no need to put that burden on PHP when MySQL has built-in functionality for that already. You should take a look at MySQL's DATEDIFF() function:
DATEDIFF() returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
An example of two dates that'd give a 7-day difference could be:
mysql> select datediff('2011-06-18','2011-06-25');
+-------------------------------------+
| datediff('2011-06-18','2011-06-25') |
+-------------------------------------+
| -7 |
+-------------------------------------+
This means that the first date occured -7 days after the first date; that's 7 days before. If you let the two arguments switch place, the result would be a positive 7.
How about considering using UNIX_TIMESTAMP? It uses the concept of elapsed time.
The "old" way to compare two or more dates is to convert then to an unix timestamp (seconds in float) using strtotime() function. For example:
if((strtotime('2011-05-10') - strtotime('2011-05-01')) > 604800)
{
echo('A week has passed');
}
if((strtotime('2011-06-10') - strtotime('2011-05-01')) > 2629743)
{
echo('A month has passed');
}
Or the "new" way is to use the DateTime class bundled with PHP 5.2 or newer. Have a look at http://php.net/manual/en/book.datetime.php.
And of course date_diff has plenty of examples.
You need to consider what you are exactly looking for.
Are you looking to filter dates older than a week? You can do that comparison on the SQL and you don't burden PHP with date comparisons.
Are you wanting a date difference? Again, I suggest putting it in SQL and just display the result.
This will give you the number of seconds between the two dates:
<?php
$time = '2011-06-20';
$timeDiff = time() - strtotime($time);
echo $timeDiff;
?>
You could divide this value by 86,400 to get the number of days, and so on.
Related
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);
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
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP:find day difference between two date(“YmdHis”) reture
What I want to do is to get day from database, current date. And check if difference between them > 1 day:
$curdate= date("Y-m-d H:i:s");
$dbdate is value stored in datetime format in db.
$dif=$curdate-dbdate;
How to check if $dif>1 day ??
Assuming the stored date is expressed in the same time zone as the server, you can convert it to a timestamp using strtotime, and compare it to strtotime("-1 day"):
if (strtotime($dbdate) < strtotime("-1 day"))
frobnicate();
You can get just the day from each date.
$day = intval($curdate= date("d"));
This will get the day as an in. Do the same for the time of the data base and you get two integer representing the day. Using that you can calculate how many days have pass.
Beware that the last line should look like this:
$dif = abs($curdate-$dbdate);
I'm working on a calendar/planner web app and I need to compare the start and end times of events before I store them in my DB. An event can only have a range of one day and between 8am and midnight. The start time always has to take place before the end time.
The post values come from the form in the following format hh:mm:ss (12:14:00) etc.. so I can store them in my database without much hassle. Is there any way I can compare these times?
Thanks a lot!
If those times are in the database, comparison operator of the database would works. For example:
SELECT * FROM table WHERE time < NOW()
In PHP, the easiest way to compare times is to convert them to timestamps, and then to compare timestamps as integers. You can use strtotime to do that conversion.
For example:
$time1 = "08:00:00";
$time2 = "09:00:00";
if (strtotime($time1) > strtotime($time2) ||
strtotime($time1) < strtotime("08:00:00")) {
...
}
If you're running PHP 5.3, you can use the diff() method of DateTime objects to get the difference in between two dates. But it's possible to do with just timestamps too (1 day = 86400 seconds)