Comparing times in the 12-hour format - php

Can someone help and give a solution to compare two times which are in the following format when received: 12:20 AM.
I have two time fields in my script which are meant to be stored in the database after validation, but after validation that the format is in correct order i want to do comparison between those two fields.
The comparison i want to do is to check if the second field not overlapping the first one.
For Example:
The first variable is named $timeStart, and holding the time value of = "05:30 PM".
The second is named $timeEnd, holding a value of = "4:00 PM".
Now, i want to do a comparison to see if the $timeEnd is before $timeStart (also putting into consideration AM/PM when comparing) if it is i dont want to echo an error, otherwise continue with the script.
I'm doing it for a Event Script, so timing has to be right :) $timeEnd has to be after $timeStart.
I sure do hope i explained it clear enough :(
Thanks for taking the time to read my complicated gibberish :)

if(function greaterDate($start_date,$end_date)
{
$start = strtotime($start_date);
$end = strtotime($end_date);
if ($start-$end > 0)
return 1;
else
return 0;
}
$time = greaterDate($start_date,$end_date))

This should help
function timediff($start, $end)
{
if($end >= $start)
{
return (round(($end-$start)/3600, 0))." Hrs ".((($end-$start)%3600)/60)." Min";
}
return false;
}
echo timediff(strtotime('yesterday 5 pm'), strtotime('today 4:30 am'));

if (strtotime($timeEnd) < strtotime($timeStart)) {
// fail
}
Only makes sense though if you're not going to allow day crossovers, obviously.

Related

Check if date is bigger than string [duplicate]

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";
}

php strtotime() values not working as expected

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.

Comparing DateTime?

I've been doing a good amount of research with this, and used a few codes to get to know how to make this work, but nothing has worked the way I wanted it to, or hasn't worked at all.
The code is:
<?php
$time1 = $user['last_active'];
$time2 = "+5 minutes";
if (strtotime($time1) > strtotime($time2)) {
echo "Online!";
}else{
echo "Offline!";
}
?>
It is supposed to compare the two variables, and find out if the last active variable is greater or less than 5 minutes, and if it is greater, appear offline. I do not know what's wrong as the NOW() updates on each page and stops if the user is not logged in. Any suggestions or help? Thanks.
The $time1 variable is coming from a fetched array that gets the ['last_active'] information that updates on each page.
I fixed my code, but it still doesn't work right, however, I think I have managed to get further than I was..
<?php
$first = new DateTime();
$second = new DateTime($user['last_active']);
$diff = $first->diff( $second );
$diff->format( '%H:%I:%S' );
if($diff->format( '%H:%I:%S' ) > (strtotime("5 minutes"))){
echo "Offline";
}else{
echo "Online";
}
?>
What can I do at this point?
Nobody pointed out that you actually have a bug. The "current time" will never be greater than "the current time +5 minutes"
Your first code sample will work right if you instead use "-5 minutes" as the "online threshold."
Also, comparing a timestamp without date to the output of strtotime() as you do in the second code is not a proper comparison. It has two problems:
Each time a new day comes around, the same time value will be repeated.
The output of strtotime is an integer representing seconds-since-epoch; the output of format() is a textual representation of hours:minutes:seconds within the current date.
As for your question how to calculate time between 2 dates / time, please view the solution on the following posts, that should give you enough information! (duplicate ? )
Calculate elapsed time in php
And here
How to get time difference in minutes in PHP
EDIT AS YOU PLEASE
<?
$first = new DateTime(); // this would hold your [last active]
//$first->modify("-6 minutes");
$second = new DateTime("NOW");
$difference = $second->diff( $first ); // second diff first
if ($difference->format('%i') > 5) { // comparing minutes only in example ( %i )
echo "The user is AFK";
} else {
echo "user might still be active";
}
?>

how to show message when countdown reached to zero?

i got one problem where i nead your help, if you have any solution please help me.
The problem is as follows:
I m using $currenttime and $settime variable to set currenttime and targettime
$currenttime = date('Y-m-d H:i:s');
$settime = "2012-o5-03 02:10:00";
$diff1 = abs(strtotime($currenttime) - strtotime($settime));
On the basis of $diff1 we are starting the countdown and countdown are working properly.
Now i want to show a message when $settime and $currenttime are equal for these i have use this code
if(strtotime($currenttime) == strtotime($settime))
{
echo "Your time begin just now";
}
but after countdown reached to zero it should show the message but it not showing, if any one have any solution plz help me.
i have seen your code there was a little mistake with declaration such o instead of 0
& the code i wrote which is working as follow....
echo $currenttime = date('Y-m-d H:i:s');
echo $settime = "2012-05-03 12:20:50";
$diff1 = abs(strtotime($currenttime) - strtotime($settime));
if($currenttime != $settime)
{
echo "Your time not yet set";
}
else
{
echo "Your time begin just now";
}
I would tend to compare for a time later than the expected trigger time in case the script is not running at the exact second that current and trigger time are equal.
if(strtotime($currenttime) >= strtotime($settime))
{
echo "Your time begin just now";
}
Don't use equal, if your script-call is a bit late, you'll never get there. use either greater then > to do it for all times that are PAST your goal, or check if the difference between the times is something small (like abs(time1 - time2) < 2), so you know your current time is closer then 2 seconds from your target time.

Compare given date with today

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";
}

Categories