Check if older or newer date than current (by month) - php

I want to check if given date (like 2012-12) is older or newer than current date.
I know how to check older month like
if(strtotime('2012-12')<strtotime('-1 Months')){
echo "true"; // got TRUE ... correct!
} else {
echo "false";
}
But what about newer ?
if(strtotime('2013-02')>strtotime('1 Months')){
echo "true";
} else {
echo "false"; // got FALSE ... incorrect !
}
I got incorrect result when checking newer date.

You forgot to add the + to your strtotime function.
if(strtotime('2013-02')>strtotime('+1 Months')){
echo "true";
} else {
echo "false";
}
Update:
Some things are weird in your question. For example 2013-02 is not a date but a reference to a month. If you want to check if this is the first day of the month use the full date notation: 2012-02-01. If you want to check if the current date into a month check the current month with date("n") (returns 1-12); and compare this to the given month, for example:
$date = "2012/02/01";
if(date("n", strtotime($date)) != date("n")) {
echo 'not current month';
}
if you want to check if this is not the current date do something like:
$date = "2012/02/01";
if(date('d-m-Y', strtotime($date)) != date('d-m-Y')) {
echo 'not current day';
}

If you want to compare a date with the current time to see if its in the past or in the future you could use
$date = '2013-02';
$now = time();
if ( strtotime($date) > $now ) {
echo 'Date is in the future';
} else {
echo 'Date is in the past';
}
Note however that if you supply a date like $date = '2013-01' i.e. without a day it will return as in the past, even though we are still in january. Be sure to take a look if this is the behaviour you want

What about comparing the strings? If you can compare directly the strings, using the ISO 8601 format yyyy-mm-dd they're always lexicographically ordered.
2012-01 < 2012-12 < 2013-01 < 2013-02 < 2014-01
(the bold one being the current)

Related

PHP Checking if outputted date is less than current date

I have the following function which works well but would like to check the returned date and compare with the current date if before current date to show something if current or in future show as normal.
Function:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
Call:
echo '<li class="list-group-item">Support Expires: ' . dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60 . '</li>');
Output:
2nd March 2016
So as not today's date and/or before today's date would like to echo a message, else just show the date.
In PHP it is very simple to compare two different dates using < = > like you normally compare numbers. The only step prior to this is below:
//Tell PHP that the value in variable is a date value
$date_1 = date_create("2017-05-29"); //This value can be any valid date format
date_1_formatted = date_format($date_1, "Y-m-d"); //This formats the date_1
//Now you can simply put the second date, for example, today.
$date_2 = date_create("2017-04-29"); //This value can be any valid date format
date_2_formatted = date_format($date_2, "Y-m-d"); //This formats the date_1
//For current date, it is simpler
$date_today_formatted = date("Y-m-d");
//Now you can compare these two dates easily
if ($date_1 < $date_today_formatted) {
echo "Date 1 falls before today.";
}
else {
echo "Date 1 falls after today.";
}
Hope this helps!
I managed to work it out using the following 2 functions:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
function checkLicenceSupport($licence_date) {
$date_now = new dateTime();
$date_set = dateFormat($licence_date, 11*60*60);
if ($date_now > $date_set) {
return 'date expired';
} else {
return 'date valied';
}
}
I have the following function which works well, but would like to
check the returned date and compare with the current date.
If it is before the current date, show something.
If it is the current date, or in future, show as normal.
I needed to rewrite your question, because lack of grammar and punctuation made it confusing. No offense intended.
Your call code has the closing parenthesis for your function call is placed wrongly.
dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60)
It is more readable to use full days or hours (in seconds):
11*86400 //(11 Days);
11*3600 //(11 Hours);
The function and code, as you have it now, will always return a date in the future of the date you've submitted via the call. (I can't tell from your question whether this was intended or not).
Currently, there is no "comparison" in your function. But your question indicates you want to compare the submitted date to the current date and then do something in certain cases.
If you are going to use a Unix timestamp, then there's no need for multiple formatting, compare the two dates in Unix, then format the result.
function dateCompare($submittedDate){
//This is only needed if your submitted date is not a unix timestamp already
$submittedDate = strtotime($submittedDate);
$currentDate = time(); // Creates timestamp of current datetime
if($submittedDate < $currentDate) {
//show something i.e. return "Support Has Expired";
}else {
return date('jS F Y', $submittedDate);
}
}
echo '<li class="list-group-item">Support Expires: '.dateCompare($purchase_data['verify-purchase']['supported_until']).'</li>';

PHP date comparison and strtotime

Using WIndows, XAMPP 5.6.8 I am building a simple web app in HTML and PHP.
I would like to compare a date retrieved from a database with today's date.
I have a function that successfully returns a string value (in the UK date format d-m-y).
My code so far is;
$expDate = get_api_data($id); // returns a string
var_dump($expDate); // this prints string(8) "31-12-19"
Using this $expDate value I would like to achieve something like;
if (strtotime('d-m-y', $expDate) > time()) { // if date > than today
echo 'date is greater than today';
}
elseif (strtotime('d-m-y', $expDate) < time()) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
Currently I am receiving date is less than today - even though the date is 31-12-19. I'm not sure if I am approaching this the correct way?
Any help would be greatly appreciated as I have alreday spent a lot of time researching answers to no avail.
I got this error when executing your code
PHP Notice: A non well formed numeric value encountered
You should look at the doc in order to make a good usage of this function: http://php.net/manual/fr/function.strtotime.php
The first param should be a time, not a format.
By the way, i prefer use DateTime class to compare dates, you can do:
<?php
$expectedDate = \DateTime::createFromFormat('d-m-y', get_api_data($id));
$nowDate = new \DateTime();
if ($expectedDate > $nowDate) { // if date > than today
echo 'date is greater than today';
}
elseif ($expectedDate < $nowDate) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
$formattedDate = DateTime::createFromFormat('d-m-y', $expDate);
$expDate= $formattedDate->getTimestamp();
if ($expDate > time()) { // if date > than today
echo 'date is greater than today';
.....
Try above code sample, try to use DateTime class if you have PHP 5.2.0 or higher http://php.net/manual/en/datetime.createfromformat.php . Then using that dateTime object you can do comparisons in a way you want e.g. in my sample I am doing it by time.
Your code will show a notice. if you turn on the php error reporting, you will observer it.

Odd Date("Y-m-d") result

Im having some bizarre results in regards to the php date() function. Basically Im getting a date from a Mysql database which is in a string format, split into three elements. This would be Day, Month, Year (15 september 2012 for example) Im ultimately comparing two dates to see if it has expired. But the issue is that only certain dates are allowing the code to work, and some do not work at all (or allow the if statement to work effectively) Below is my code, any help would be great.
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year'))) ;
if ($expire < $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
Im sure its something simple, but for some reason I cannot solve it.
You need to compare the Unix timestamps.
$today = time();
$expire = strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year')) ;
if ($expire > $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
It looks like strtotime is expected a US date format; you need to swap the month and the day around to generate a valid date:
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_month')."-".
$this->getData('date_day')."-".$this->getData('date_year'))) ;
On the other hand, see Stephen305's answer - it's a much better solution to your problem.

Comparing a date to current server date using PHP

I am using the following code to attempt to compare the current date with a date entry in a mySql database. It's code that I have found online and adapted as all the examples I have found hard-code the date to compare the current date with.
The trouble is even dates in the future are being marked as expired and I can't understand why this would be.
I am afraid that I am still new to PHP, so I may be making a schoolboy error!
$exp_date = KT_formatDate($row_issue_whatson1['dateToShow']);
$todays_date = date("d-m-Y");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) { echo "Not expired"; } else { echo "expired"; }
Any help would be most appreciated.
I should add that the date time format used in the database entries is dd/mm/yyyy
Instead of making a string then converting it to a timestamp, simply use mktime:
<?php
$today = mktime(
0, // hour
0, // minute
0 // seconds
);
?>
The rest of the values will be filled according to today's date. If this still gives problems, put in some echo's for the values of $exp_date and $expiration_date.
Edit
Since this solved the problem, the discrepancy you were seeing was because you were doing the opposite with date('d-m-Y'). You were asking for the current date and the time values are then filled in with the current time. The expiration date in the database is likely set at midnight. With both dates being equal, and it being say 11am now, you are comparing if (00:00:00 > 11:00:00) which fails.
$exp_date = 14/05/2011 // todays date, int
$server_date = server.date() // servers date, int
// check exp_date against server date
if ( $server > $exp_date)
{ echo "Sorry your 'service' has expired"; }
else
{ echo "Welcome 'members_name' to StackOverflow"; }
Try that. However you need the right date format, as server.date() is probably different in PHP.
If problem still persists I would check whether your dates are strings or integers or both. That could possibly be the issue.
Hope that helps.
DL.
Your function does not seem to be valid.
function KT_formatDate( $exp_date){
$exp_date = strtotime($exp_date);
$now = time();
if ($now > $exp_date)
return 'expired';
else
return ' Not expired';
}
$response = KT_formatDate($row_issue_whatson1['dateToShow']);

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