如何在php中将日期时间的第一个对象与另一个日期时间对象进行比较

如何在php中将日期时间的第一个对象与另一个日期时间对象进行比较

问题描述:

here I am using one date time object is this

 $cdate  = date('d/m/Y h:i:sa')  

and another date time object is this

$udate = date("d/m/Y h:i:sa", strtotime("72 hours"));

for comparing I am using this condition

 if($cdate >= $udate)

but problem is this...in this case its only comparing only day not entire date and time.

这里我使用一个日期时间对象是这个 p>

   $ cdate = date('d / m / Y h:i:sa')
  code>  pre> 
 
 

另一个日期时间对象是这个 p>

  $ udate = date(“d / m / Y h:i:sa”,strtotime(“72小时”)); 
  code>  pre> 
 
 

比较我正在使用这个条件 p>

  if($ cdate> = $ udate)
  code>  pre> 
 
 

但问题 这是......在这种情况下,它只比较一天而不是整个日期和时间。 p> div>

The strings returned from date() are only comparable in certain circumstances. You should use DateTime() whose objects are always comparable:

$cdate  = new DateTime();
$udate = new DateTime('+3 days');
if($cdate >= $udate) {

}

if(strtotime($cdate) >= strtotime($udate)){
// your condition
}

Hope it helps :)

The date() function returns a string - not a DateTime object. As such, the >= comparison you are doing is a string comparison, not a comparison of the dates/times.

If you really want to do string comparison, use a format where such sorting will make sense, such as ISO 8601. You can do this trivially with the format 'c'.

Much better, however, would be to compare actual DateTime objects or the integer timstamps (such as what you would get from time()).

You don't compare date times and there are no objects (like in OOP) in your code. $cdate and $udate are strings, that's why they are compared using the strings comparison rules (i.e. the dictionary order).

You can either use timestamps (that are just integer numbers of seconds):

// Use timestamps for comparison and storage
$ctime = time();
$utime = strtotime("72 hours");
// Format them to strings for display
$cdate = date('d/m/Y h:i:sa', $ctime);
$udate = date('d/m/Y h:i:sa', $utime);
// Compare timestamps
if ($ctime < $utime) {
    // Display strings
    echo("Date '$cdate' is before date '$udate'.
");
}

Or you can use objects of type DateTime:

$cdate = new DateTime('now');
$udate = new DateTime('72 hours');

// You can compare them directly
if ($cdate < $udate) {
    // And you can ask them to format nicely for display
    echo("Date '".$cdate->format('d/m/Y h:i:sa')."' is before date '".
         $udate->format('d/m/Y h:i:sa')."'
");
}

Your code wrong for comparing dates, because date returns string.

Try this:

$cdate = new DateTime();
$udate = new DateTime('72 hours');

if($udate > $cdate) {
    echo 'something';
}