In my PHP application I'm trying to compare date time values like the following:
if($datetime_from_db < date('Y-m-d H:i:s'))
{
// then do something
}
Both values are in the same format. What I can't figure out is why it only compares the date and ignores the time. Both the date and the time values are important for me but I don't know how to make it work.
Comparing a string like "2011-02-14 15:46:00" to another string doesn't actually compare dates, it compares two strings according string parsing numeric rules. You will need to compare actual numeric timestamps:
strtotime($datetime_from_db) < time()
If you want this to work with dates past 2038, you can't use strtotime() or time().
See this question for the explanation.
A better approach:
new DateTime($datetime_from_db) < new DateTime();
This may help you.
$today = date("m-d-Y H:i:s");
$thisMonth =date("m");
$thisYear = date("y");
$expectedDate = $thisMonth."-08-$thisYear 23:58:00";
//pr($today);
//pr($expectedDate);
if (strtotime($expectedDate) > strtotime($today)) {
echo "Expected date is greater then current date";
return ;
} else
{
echo "Expected date is lesser then current date";
}
Here is a solution where we use strtotime. I give two examples.
First one comparing the whole timestamp. Second one is just compare the date.
<?php
$date = "2022-10-06 17:49:10"; // string. can set any current timestamp
#example 1 - compare the date and time Y-m-d H:i:s
if(date("Y-m-d H:i:s" , strtotime($date)) >= date("Y-m-d H:i:s")){
echo "the date checked is bigger than today";
}else{
echo "the date checked is smaller than today";
}
#example 2 - compare the date only Y-m-d
if(date("Y-m-d" , strtotime($date)) == date("Y-m-d")){
echo "same day is true";
}else{
echo "same day is false";
}
Related
I want to compare two dates and time values in PHP. One date is coming from MySQL, and second one is the current date. I want to run some code when both dates are the same. I tried the code below, but condition satisfies any time which is wrong.
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
}else{
}
What is wrong with the code? I also tried to covert both dates with strtotime() before comparing, but it gave me the same issue. The above condition satisfies any time even if both dates are different.
Try this :
$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if(strtotime($current_datetime) == strtotime($send_date)){
//I want to run some code here
}else{
}
Hope it helps !!!!
One way is to fetch the Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) from MySQL, then operate on the numbers:
$row = get_db_row("SELECT UNIX_TIMESTAMP(send_date) AS send_date_ts
FROM table WHERE $condition");
$hours = (int) ($row['send_date_ts'] / 3600);
$current_hours = (int) (time() / 3600);
if ($hours == $current_hours) {
// current hour
}
Timestamps are convenient because:
there is no need to take the format into account;
operations on numbers are usually faster;
the code looks cleaner.
Try this. On my server is working just great I've got something else because they aren't equal. Date which I receive from database is type datetime format 2015-04-13 09:03:49
<?php
$current_datetime = strtotime(date('Y-m-d H:i'));
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
//I want to run some code here
echo 'something';
}else{
echo 'something else';
}
Output:
echo $current_datetime . '<br/>';
2016-10-17 09:19
echo $send_date .'<br/>';
2015-04-13 09:03
// result
something else
I've created an If an Else Statement but it doesn't work properly.
I have some dates within my SQL which have been retrieved and stored in variables using PHP.
I'm comparing the current date with the dates from the database but for some reason, it thinks for example that 29-09-2015 if LESS THAN 31-01-2015.
I can understand that the format could be the issue d,m,Y but I thought I'd corrected that already.
Here's the code:
$today = date('d-m-Y');
$date = $row['respondby'];
$euDate= date("d-m-Y", strtotime($date));
<?php
if($today < $euDate){ echo "<td>". $today." is less than ". $euDate ."</td>";
}
else{
echo"<td>Lost somewhere in between ?!?!?! :S </td>";
}
?>
As a result it prints
29-09-2015 is less than 30-06-2015
today's date was 29-09-2015 and one of the dates was in the data was this one as shown.
Thank you everyone that helps.
Comparison of dates as strings uses lexicographical order, hence your result is "correct".
Instead of d-m-Y format, try to use Y-m-d, this guarantees proper ordering.
$today = date('Y-m-d');
$date = $row['respondby'];
$euDate= date("Y-m-d", strtotime($date));
if($today < $euDate) { [...] }
Or, you can use Date objects instead:
$today = new Date('now');
$euDate= new Date($row['respondby']);
if($today < $euDate) { [...] }
The date to be checked is as follows :
$submission_date = 12-25-2014; //The date in mm-dd-yyyy format that is to be tested against today's date
Now I want to echo the error message since the date contained in a variable $submission_date is a future date.
How should I do this efficiently and effectively using PHP?
Thanks in advance.
Many ways to do this (use DateTime::createFromFormat() to control exact format of input dates, for example) but perhaps the simplest that suits the example is:
$isFuture = (strtotime($submission_date) > strtotime($_POST['current_date']))
Note that OP changed the question. If desired date to test against is not in $_POST array, just replace strtotime($_POST['current_date']) with time() to use current system time.
To compare against current date, disregarding time of day, use:
$today = new DateTime(date("Y-m-d"));
// $today = new DateTime("today"); // better solution courtesy of Glavić
// see http://php.net/manual/en/datetime.formats.relative.php for more info
$today_timestamp = $today->getTimestamp();
If posted format is in m-d-Y, then you cannot convert it to unix timestamp directly with strtotime() function, because it will return false.
If you need to use strtotime() then change the input format to m/d/Y by simple str_replace().
On the other hand, you could use DateTime class, where you can directly compare objects:
$submission_date = DateTime::createFromFormat('!m-d-Y', $submission_date);
$today_date = new DateTime('today');
if ($submission_date > $today_date) {
echo "submission_date is in the future\n";
}
demo
With PHP DateTime you can check whether the input date is future or old w.r.to the todate.
$submission_date = DateTime::createFromFormat('m-d-Y', $submission_date);
$submission_date = $submission_date->format('Y-m-d');
$current_date = new DateTime('today');
$current_date = $current_date->format('Y-m-d');
if ($submission_date > $current_date)
{
echo "Future date";
}
else
{
echo "Old date";
}
$todaysDate = date("Y-m-d");
$maxBookingDate=strtotime('+2 weeks', $todaysDate);
$dateEntered = DateTime::createFromFormat('d/m/Y', $_POST["Date"]);
$tableDate =$dateEntered->format('Y-m-d');
if ($tableDate < $todaysDate){
echo "Date must be in the future";
}
if ($tabledate > $maxBookingDate){
echo "Date must be no more than 2 weeks in advance";
}
Date comparison to make sure that the date a user enters is no more than two weeks in advance isn't working, what have I done wrong?
You can just use DateTime classes all through out so that its easier to compare:
$todaysDate = new DateTime();
$maxBookingDate = new DateTime('+2 weeks');
$dateEntered = DateTime::createFromFormat('d/m/Y', $_POST['Date']);
if ($dateEntered < $todaysDate){
echo "Date must be in the future";
} elseif ($dateEntered > $maxBookingDate){
echo "Date must be no more than 2 weeks in advance";
}
In your code:
$todaysDate is a string, and you fed it inside strtotime() as your second parameter which is incorrect usage. The second parameter requires numeric value (timestamp).
Inside your if else statement, you're comparing strings. You should be comparing them as timestamps or DateTime objects instead, like the answer above.
i am struggling for a long time to set a specific date but i am not getting correct out put.
i want to get date from user and compare that date with the date 15 days older then today. if it is older than 15 days then convert to today else print what it is.
$todaydate= $_GET['date'];// getting date as 201013 ddmmyy submitted by user
$todaydate=preg_replace("/[^0-9,.]/", "", $todaydate);
$today =date("dmy"); //today ddmmyy
$older= date("dmy",strtotime("-15 day")); // before 15 days 051013
if ($todaydate <= $older){
$todaydate= $today;}
problem is, it is taking date as number and giving wrong result.
Comparing date strings is a bit hacky and prone to failure. Try comparing actual date objects
$userDate = DateTime::createFromFormat('dmy', $_GET['date']);
if ($userDate === false) {
throw new InvalidArgumentException('Invalid date string');
}
$cmp = new DateTime('15 days ago');
if ($userDate <= $cmp) {
$userDate = new DateTime();
}
Also, strtotime has some severe limitations (see http://php.net/manual/function.strtotime.php#refsect1-function.strtotime-notesand) and is not useful in non-US locales. The DateTime class is much more flexible and up-to-date.
try this one:
<?php
$todaydate = date(d-m-Y,strtotime($_GET['date']));
$today = date("d-m-Y");
$older= date("d-m-Y",strtotime("-15 day"));
if (strtotime($todaydate) <= strtotime($older))
{
$todaydate= $today;
}
?>
$previousDate = "2012-09-30";
if (strtotime($previousDate) <= strtotime("-15 days")) {
//the date in $previousDate is earlier or is equal to the date 15 days before from today
}