I have following
$var = "2010-01-21 00:00:00.0"
I'd like to compare this date against today's date (i.e. I'd like to know if this $var is before today or equals today or not)
What function would I need to use?
strtotime($var);
Turns it into a time value
time() - strtotime($var);
Gives you the seconds since $var
if((time()-(60*60*24)) < strtotime($var))
Will check if $var has been within the last day.
That format is perfectly appropriate for a standard string comparison e.g.
if ($date1 > $date2){
//Action
}
To get today's date in that format, simply use: date("Y-m-d H:i:s").
So:
$today = date("Y-m-d H:i:s");
$date = "2010-01-21 00:00:00";
if ($date < $today) {}
That's the beauty of that format: it orders nicely. Of course, that may be less efficient, depending on your exact circumstances, but it might also be a whole lot more convenient and lead to more maintainable code - we'd need to know more to truly make that judgement call.
For the correct timezone, you can use, for example,
date_default_timezone_set('America/New_York');
Click here to refer to the available PHP Timezones.
Here you go:
function isToday($time) // midnight second
{
return (strtotime($time) === strtotime('today'));
}
isToday('2010-01-22 00:00:00.0'); // true
Also, some more helper functions:
function isPast($time)
{
return (strtotime($time) < time());
}
function isFuture($time)
{
return (strtotime($time) > time());
}
You can use the DateTime class:
$past = new DateTime("2010-01-01 00:00:00");
$now = new DateTime();
$future = new DateTime("2021-01-01 00:00:00");
Comparison operators work*:
var_dump($past < $now); // bool(true)
var_dump($future < $now); // bool(false)
var_dump($now == $past); // bool(false)
var_dump($now == new DateTime()); // bool(true)
var_dump($now == $future); // bool(false)
var_dump($past > $now); // bool(false)
var_dump($future > $now); // bool(true)
It is also possible to grab the timestamp values from DateTime objects and compare them:
var_dump($past ->getTimestamp()); // int(1262286000)
var_dump($now ->getTimestamp()); // int(1431686228)
var_dump($future->getTimestamp()); // int(1577818800)
var_dump($past ->getTimestamp() < $now->getTimestamp()); // bool(true)
var_dump($future->getTimestamp() > $now->getTimestamp()); // bool(true)
* Note that === returns false when comparing two different DateTime objects even when they represent the same date.
To complete BoBby Jack, the use of DateTime OBject, if you have php 5.2.2+ :
if(new DateTime() > new DateTime($var)){
// $var is before today so use it
}
$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');
var_dump(strtotime($today) > strtotime($expiry)); //false or true
One caution based on my experience, if your purpose only involves date then be careful to include the timestamp. For example, say today is "2016-11-09". Comparison involving timestamp will nullify the logic here. Example,
// input
$var = "2016-11-09 00:00:00.0";
// check if date is today or in the future
if ( time() <= strtotime($var) )
{
// This seems right, but if it's ONLY date you are after
// then the code might treat $var as past depending on
// the time.
}
The code above seems right, but if it's ONLY the date you want to compare, then, the above code is not the right logic. Why? Because, time() and strtotime() will provide include timestamp. That is, even though both dates fall on the same day, but difference in time will matter. Consider the example below:
// plain date string
$input = "2016-11-09";
Because the input is plain date string, using strtotime() on $input will assume that it's the midnight of 2016-11-09. So, running time() anytime after midnight will always treat $input as past, even though they are on the same day.
To fix this, you can simply code, like this:
if (date("Y-m-d") <= $input)
{
echo "Input date is equal to or greater than today.";
}
Few years later, I second Bobby Jack's observation that last 24 hrs is not today!!! And I am surprised that the answer was so much upvoted...
To compare if a certain date is less, equal or greater than another, first you need to turn them "down" to beginning of the day. In other words, make sure that you're talking about same 00:00:00 time in both dates.
This can be simply and elegantly done as:
strtotime("today") <=> strtotime($var)
if $var has the time part on 00:00:00 like the OP specified.
Replace <=> with whatever you need (or keep it like this in php 7)
Also, obviously, we're talking about same timezone for both.
For list of supported TimeZones
$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
(the w3schools example, it works perfect)
Expanding on Josua's answer from w3schools:
//create objects for the dates to compare
$date1=date_create($someDate);
$date2=date_create(date("Y-m-d"));
$diff=date_diff($date1,$date2);
//now convert the $diff object to type integer
$intDiff = $diff->format("%R%a");
$intDiff = intval($intDiff);
//now compare the two dates
if ($intDiff > 0) {echo '$date1 is in the past';}
else {echo 'date1 is today or in the future';}
I hope this helps. My first post on stackoverflow!
Some given answers don't have in consideration the current day!
Here it is my proposal.
$var = "2010-01-21 00:00:00.0"
$given_date = new \DateTime($var);
if ($given_date == new \DateTime('today')) {
//today
}
if ($given_date < new \DateTime('today')) {
//past
}
if ($given_date > new \DateTime('today')) {
//future
}
Compare date time objects:
(I picked 10 days - Anything older than 10 days is "OLD", else "NEW")
$now = new DateTime();
$yourdate = new DateTime("2021-08-24");
$diff=date_diff($yourdate,$now);
$diff_days = $diff->format("%a");
if($diff_days > 10){
echo "OLD! " . $yourdate->format('m/d/Y');
}else{
echo "NEW! " . $yourdate->format('m/d/Y');
}
If you do things with time and dates Carbon is you best friend;
Install the package then:
$theDay = Carbon::make("2010-01-21 00:00:00.0");
$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))
lt = less than,
gt = greater than
As in the question:
$theDay->gt(Carbon::today()) ? true : false;
and much more;
Try this:
if (date("Y-m-d",strtotime($funding_dt)) >= date("Y-m-d",strtotime('31-01-2007')))
{
echo "ok";
} else {
echo "not";
}
Related
I work on one project with PHP and Mysql and I need to calculate the ages but I need delete the hours, minutes and seconds part. Here is an example:
The date of birth 2018-03-06 17:35:00 but
I need 2018-03-06 00:00:00
Here is my code:
function FetchAgeCaduce($MaxDias=3){
$fechaInicial = time();//date("Y-m-d");
$fecha = date("d/m/Y",$FechaFinal);
$fechaInicial = strtotime("d/m/Y",$fecha);
for ($i=0; $i<$MaxDias; $i++)
{
$Segundos = $Segundos + 86400;
$caduca = time()+$Segundos;//date("D",time()+$Segundos);
$var = date("D",$caduca);
if ($var == "Sat")
{
$i--;
}
else if ($var == "Sun")
{
$i--;
}
else
{
$FechaFinal = time()+$Segundos;
}
}
return $FechaFinal;
}
How can I work on it to get the expected result?
The right way / The MySQL way:
Store your data as DATE in MySQL, not DATETIME. DATE itself is described here. It does not store time, so you'll always have 00:00:00 as default.
The less right way / The PHP way:
Jay, Zeus, Freaking, K. Reist. Learn to use DateTime already, stop using date! It's like every second question here and noone learns DateTime!
Use it!
$dt = new DateTime();
echo $dt->format("Y-m-d 00:00:00");
The output:
2018-03-06 00:00:00
P.S. $FechaFinal on line 5 is not defined.
You can format the date on either the application or database layer.
Using MySQL
You can use MySQL DATE_FORMAT Function
to parse the date into the wanted format.
SELECT DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00') dob;
See DEMO on SQL Fiddle.
Using PHP
Say you don't want to format the date in the database layer, may be because you would need to use the time part in some other calculations. Use the date functions as illustrated below:
$dt = new DateTime();
echo $dt->format("Y-m-d 00:00:00");
//getting the expected date from the formatted string
$formateDate = DateTime::createFromFormat('Y-m-d H:i:s', $dt->format("Y-m-d 00:00:00"));
I am displaying a number of dates using PHP and I need to hide them when a certain date has expired.
I am using an IF statement to run this but it doesn't seem to be working.
Any suggestions would be great
<?PHP if('09-19-2016'<DATE('m-d-Y') || $_SESSION['role'] == 'Administrator') echo('<li>Week 2 - W/C 12/09/2016</li>');?>
When you're doing
'09-19-2016' < date('m-d-Y')
You're ending up comparing two strings, these can't be evaluated as "greater than" or "less than". You'll need to convert it to timestamps or use DateTime objects to do it. Also, the date format isn't correct.
<?php
$date_string = "09/19/2016";
// Using objects
$current_date = new DateTime();
$your_date = new DateTime($date_string);
if ($your_date < $current_date || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
// Using timestamps
if (strtotime($date_string) < time() || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
Choose either one of the above - both will work, although I find objects easier to work with.
From your comments,
hide the date if the date has passed
Note that when using the less than operator <, doing $date < $now will evaluate to true if the date is in the past, and hide the content if the date is in the future. If you desire the opposite behavior, you just use the greater than operator <.
Here's a live demo: https://3v4l.org/N74G2
References
http://php.net/datetime.construct
http://php.net/strtotime
http://php.net/language.operators.comparison
You need to parse your date from your format '09-19-2016' to a timestamp or DateTime object, which PHP will be able to compare as a date. You can use PHP's date_parse_from_format() to do so.
For example:
$date = '09-19-2017';
$parsed = date_parse_from_format('m-d-Y', $date);
$timestamp = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
if ($timestamp < time()) {
echo 'older';
} else {
echo 'newer';
}
This will give you the correct answer while keeping your current format. You can see an working example here: https://3v4l.org/NIoId
this code keeps telling me that $lasUpdate is always greater than $yesterday no matter the change i make to $yesterday result is (12/31/14 is greater than 01/19/15 no update needed). i feel like i'm missing something simple thank you in advance it is greatly appreciated.
$result['MAX(Date)']='12/31/14';
$lastUpdate = date('m/d/y', strtotime($result['MAX(Date)']));
$yesterday = date('m/d/y', strtotime('-1 day'));
if($lastUpdate<$yesterday){echo $lastUpdate.'is less '.$yesterday.'<br>'.'update needed';}
if($lastUpdate>=$yesterday){echo $lastUpdate.'is greater than '.$yesterday.'<br>'.'no update needed';
You have fallen victim to PHP type juggling with strings. A date function has a return value of a string. You cannot compare dates in their string format since PHP will juggle strings into integers in the context of a comparison. The only exception is if the string is a valid number. In essence, you are doing:
if ('12/31/14' < '01/19/15') { ... }
if ('12/31/14' >= '01/19/15') { ... }
Which PHP type juggles to:
if (12 < 1) { ... }
if (12 >= 1) { ... }
And returns false on the first instance, and true on the second instance.
Your solution is to not wrap date around the strtotime functions, and just use the returned timestamps from the strtotime functions themselves to compare UNIX timestamps directly:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
You will however want to use date when you do the echo back to the user so they have a meaningful date string to work with.
Try something like this:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
if ($lastUpdate < $yesterday) { /* do Something */ }
12/31/14 is greater than 01/19/15
Because 1 is greater than 0. If you want to compare dates that way you will need to store them in a different format (from most to least significant digit), for example Ymd.
Or store the timestamps you are making in the different variables and compare them.
I'm trying to determine when a user has last logged on. My current method works but is there an easier way of determining this so that I could determine last X hours etc?
This is what I currently use:
$last_login_di = getdate($last_login);
$now = time();
$now_di = getdate($now);
$today = mktime(0,0,0,$now_di['mon'],$now_di['mday'], $now_di['year']);
if ($last_login > $today) {
return 'Online Today';
}
$yesterday = $now-86400;
$yesterday_di = getdate($yesterday);
$yesterday = mktime(0,0,0,$yesterday_di['mon'],$yesterday_di['mday'], $yesterday_di['year']);
if ($last_login > $yesterday) {
return 'Online Yesterday';
}
if (($now - $last_login < 604800) ) {
return 'Online This Week';
}
....
Try strtotime() (see relative formats it accepts) or better yet, the DateTime, DateInterval classes.
For example, the $yesterday variable creation is prone errors near datetime savings. strtotime() handles this properly with:
$yesterday = strtotime('-1 day');
While the $last_login check can be written like:
if (strtotime('-1 week') < $last_login) {
// ...
}
If you need to support different timezones you probably better of with the DateTime objects though.
Have a look at the DateTime and related classes DateTime Book on php.net. The DateInterval class may be of particular use to you.
How do you get the date? Using MySQL? Use UNIX_TIMESTAMP for dates, eg SELECT UNIX_TIMESTAMP(last_login) AS last_login_timestamp FROM ... Then you can better calculate in PHP (using date_diff)
I think your code's fine. But the $yesterday var is wrong.
It should be:
$yesterday = $today - 86400;
In your code $yesterday means $a_day_ago.
The same for the last week.
You should heavily use the date objects built-in with PHP.
$now = new DateTime();
$yesterday = new DateTime('yesterday');
$lastWeek = new DateTime('last week');
Now you are able to to any comparison logic you want, using the basic comparison operators:
if ($last_login > $now) {
...
} else if ($last_login > $yesterday) {
...
} else if ($last_login > $lastWeek) {
...
} else {
...
}
If you choose not to use the objects, try to avoid the time() function. That makes unit testing impossible. Tests should never depend on environment.
Use $_SERVER['REQUEST_TIME'] instead so you can mock it later.
I have following
$var = "2010-01-21 00:00:00.0"
I'd like to compare this date against today's date (i.e. I'd like to know if this $var is before today or equals today or not)
What function would I need to use?
strtotime($var);
Turns it into a time value
time() - strtotime($var);
Gives you the seconds since $var
if((time()-(60*60*24)) < strtotime($var))
Will check if $var has been within the last day.
That format is perfectly appropriate for a standard string comparison e.g.
if ($date1 > $date2){
//Action
}
To get today's date in that format, simply use: date("Y-m-d H:i:s").
So:
$today = date("Y-m-d H:i:s");
$date = "2010-01-21 00:00:00";
if ($date < $today) {}
That's the beauty of that format: it orders nicely. Of course, that may be less efficient, depending on your exact circumstances, but it might also be a whole lot more convenient and lead to more maintainable code - we'd need to know more to truly make that judgement call.
For the correct timezone, you can use, for example,
date_default_timezone_set('America/New_York');
Click here to refer to the available PHP Timezones.
Here you go:
function isToday($time) // midnight second
{
return (strtotime($time) === strtotime('today'));
}
isToday('2010-01-22 00:00:00.0'); // true
Also, some more helper functions:
function isPast($time)
{
return (strtotime($time) < time());
}
function isFuture($time)
{
return (strtotime($time) > time());
}
You can use the DateTime class:
$past = new DateTime("2010-01-01 00:00:00");
$now = new DateTime();
$future = new DateTime("2021-01-01 00:00:00");
Comparison operators work*:
var_dump($past < $now); // bool(true)
var_dump($future < $now); // bool(false)
var_dump($now == $past); // bool(false)
var_dump($now == new DateTime()); // bool(true)
var_dump($now == $future); // bool(false)
var_dump($past > $now); // bool(false)
var_dump($future > $now); // bool(true)
It is also possible to grab the timestamp values from DateTime objects and compare them:
var_dump($past ->getTimestamp()); // int(1262286000)
var_dump($now ->getTimestamp()); // int(1431686228)
var_dump($future->getTimestamp()); // int(1577818800)
var_dump($past ->getTimestamp() < $now->getTimestamp()); // bool(true)
var_dump($future->getTimestamp() > $now->getTimestamp()); // bool(true)
* Note that === returns false when comparing two different DateTime objects even when they represent the same date.
To complete BoBby Jack, the use of DateTime OBject, if you have php 5.2.2+ :
if(new DateTime() > new DateTime($var)){
// $var is before today so use it
}
$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');
var_dump(strtotime($today) > strtotime($expiry)); //false or true
One caution based on my experience, if your purpose only involves date then be careful to include the timestamp. For example, say today is "2016-11-09". Comparison involving timestamp will nullify the logic here. Example,
// input
$var = "2016-11-09 00:00:00.0";
// check if date is today or in the future
if ( time() <= strtotime($var) )
{
// This seems right, but if it's ONLY date you are after
// then the code might treat $var as past depending on
// the time.
}
The code above seems right, but if it's ONLY the date you want to compare, then, the above code is not the right logic. Why? Because, time() and strtotime() will provide include timestamp. That is, even though both dates fall on the same day, but difference in time will matter. Consider the example below:
// plain date string
$input = "2016-11-09";
Because the input is plain date string, using strtotime() on $input will assume that it's the midnight of 2016-11-09. So, running time() anytime after midnight will always treat $input as past, even though they are on the same day.
To fix this, you can simply code, like this:
if (date("Y-m-d") <= $input)
{
echo "Input date is equal to or greater than today.";
}
Few years later, I second Bobby Jack's observation that last 24 hrs is not today!!! And I am surprised that the answer was so much upvoted...
To compare if a certain date is less, equal or greater than another, first you need to turn them "down" to beginning of the day. In other words, make sure that you're talking about same 00:00:00 time in both dates.
This can be simply and elegantly done as:
strtotime("today") <=> strtotime($var)
if $var has the time part on 00:00:00 like the OP specified.
Replace <=> with whatever you need (or keep it like this in php 7)
Also, obviously, we're talking about same timezone for both.
For list of supported TimeZones
$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
(the w3schools example, it works perfect)
Expanding on Josua's answer from w3schools:
//create objects for the dates to compare
$date1=date_create($someDate);
$date2=date_create(date("Y-m-d"));
$diff=date_diff($date1,$date2);
//now convert the $diff object to type integer
$intDiff = $diff->format("%R%a");
$intDiff = intval($intDiff);
//now compare the two dates
if ($intDiff > 0) {echo '$date1 is in the past';}
else {echo 'date1 is today or in the future';}
I hope this helps. My first post on stackoverflow!
Some given answers don't have in consideration the current day!
Here it is my proposal.
$var = "2010-01-21 00:00:00.0"
$given_date = new \DateTime($var);
if ($given_date == new \DateTime('today')) {
//today
}
if ($given_date < new \DateTime('today')) {
//past
}
if ($given_date > new \DateTime('today')) {
//future
}
Compare date time objects:
(I picked 10 days - Anything older than 10 days is "OLD", else "NEW")
$now = new DateTime();
$yourdate = new DateTime("2021-08-24");
$diff=date_diff($yourdate,$now);
$diff_days = $diff->format("%a");
if($diff_days > 10){
echo "OLD! " . $yourdate->format('m/d/Y');
}else{
echo "NEW! " . $yourdate->format('m/d/Y');
}
If you do things with time and dates Carbon is you best friend;
Install the package then:
$theDay = Carbon::make("2010-01-21 00:00:00.0");
$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))
lt = less than,
gt = greater than
As in the question:
$theDay->gt(Carbon::today()) ? true : false;
and much more;
Try this:
if (date("Y-m-d",strtotime($funding_dt)) >= date("Y-m-d",strtotime('31-01-2007')))
{
echo "ok";
} else {
echo "not";
}