Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP date time greater than today

Tags:

date

php

please help what's wrong with my code? It always returns that today's date is greater than '01/02/2016' wherein 2016 is greater than in 2015.

<?php $date_now = date("m/d/Y");  $date = date_create("01/02/2016"); $date_convert = date_format($date, "m/d/Y");  if ($date_now > $date_convert) {     echo 'greater than'; } else {     echo 'Less than'; } 

P.S: 01/02/2016 is coming from the database.

like image 725
Nixxx27 Avatar asked Sep 18 '15 01:09

Nixxx27


People also ask

How can I check if a date is greater than today in php?

php $date_now = time(); //current timestamp $date_convert = strtotime('2022-08-01'); if ($date_now > $date_convert) { echo 'greater than'; } else { echo 'Less than'; } ?> Show activity on this post.

How to compare time and date in php?

Compare Dates in PHP (Object-Oriented Style)$past = new DateTime( "18 May 2021" ); $now = new DateTime( "now" ); $dist_past = new DateTime( "2002-09-21 18:15:00" ); $dist_future = new DateTime( "12-09-2036" );

How to two date compare in php?

we can analyze the dates by simple comparison operator if the given dates are in a similar format. <? php $date1 = "2018-11-24"; $date2 = "2019-03-26"; if ($date1 > $date2) echo "$date1 is latest than $date2"; else echo "$date1 is older than $date2"; ?>


1 Answers

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php  $date_now = date("Y-m-d"); // this format is string comparable  if ($date_now > '2016-01-02') {     echo 'greater than'; }else{     echo 'Less than'; } 

Demo

Or

<?php  $date_now = new DateTime();  $date2    = new DateTime("01/02/2016");  if ($date_now > $date2) {     echo 'greater than'; }else{     echo 'Less than'; } 

Demo

like image 197
John Conde Avatar answered Sep 22 '22 23:09

John Conde