PHP date comparison (2 weeks) - php

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

Related

Check if date expression ("d-m" without leading zeros) is today

I want to compare current date's day and month with subscription date's day and month only.
For example:
current date(d-m) = 3-6
And I want compare it with any other d-m
How should I do it in PHP
In my project condition is like birth date in which we don't compare year.
The trick in this is to let the month come first. This way PHP can compare the numbers by highest value. Take a look at the following example:
$aDate = DateTime::createFromFormat('m-d', '05-20');
$bDate = DateTime::createFromFormat('m-d', '06-29');
if ($aDate->format('md') > $bDate->format('md')) {
echo "'aDate' is bigger than 'bDate'";
}
use like
$current_date = date("d-m");
$subscription = "03-06-2016";
$subscription_date = date("d-m", strtotime($subscription));
if($current_date ==$subscription_date)
{
echo "date is equal";
}else
{
echo "date is not equal";
}
If you only need to check if the j-n date is the same as the current date, then you don't need to make more than one function call. Because you are not comparing greater than or less than, the format of your input is unimportant.
Code: (Demo)
$subscription = '29-11';
var_export(date("j-n") === $subscription);
// at the moment, the result is true
j is today's day of the month without any leading zeros and
n is today's month without any leading zeros.
Use DateTime() PHP objects.
Considering you have an array with user info from mysql query result: ($userData['suscriptionDate'])
$today = new DateTime();
$userSuscription = new DateTime($userData['suscriptionDate']);
if ( $today->format('d') == $userSuscription->format('d') && $today->format('m') == $userSuscription->format('m')) {
echo 'Congratulations!!';
}
Use DATE_FORMAT() function to extract part of date:
Ref: http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format
SELECT * from table_name WHERE DATE_FORMAT(subscription_date, '%d-%m') = "05-05";
I think, more elegant way to compare, especially when you have a full date with time is diff function of Datetime class:
$d1 = new Datetime();
$d2 = new Datetime('+3 months +2 days +3 hours');
$diff = $d1->diff($d2);
var_dump($diff->d); // 2
var_dump($diff->m); // 2
// or have a comparison as a string
var_dump($diff->format('Difference is in %R%a days'));
// output: Difference is in 63 days
Enjoy! Link to doc
This may help you
$sdate = $row['subscription_date'];
$date1 = date("m-d");
$date2 = date("m-d",strtotime($sdate)) ;
if ($date1 == $date2) {
}

Comparison Operators for Dates in PHP retrieved from SQL not working

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) { [...] }

PHP date() - error in finding date in between

I'm using the following code to see if a date falls between 2 other dates.
public function dateCompare($date1, $date2)
{
$interimDate = date('d/m/Y');
$StartDate = DateTime::createFromFormat('d/m/Y', $date1);
$EndDate = DateTime::createFromFormat('d/m/Y', $date2);
if ($interimDate > $StartDate && $interimDate < $EndDate)
{
echo 'Falls during given period';
}
else {
echo 'Does not fall during given period';
}
The two dates passed as follows
dateCompare('01/08/14', '30/12/14');
For some reason I continually get the message that todays date does not fall between the given period. I have checked the servers datetime and it is correct. Is anyone able to point out what exactly is causing the error?
You have a 2 letter years, so it should be lower case y for your format: d/m/y.
Also, make $interimDate equal to a new DateTime() object so you can compare properly.

PHP date compare older than 15 days

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
}

PHP Compare datetime values

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

Categories