Board index   FAQ   Search  
Register  Login
Board index PHP PHP General

how php compare two DateTime object

General discussions related to php

Moderators: macek, egami, gesf

how php compare two DateTime object

Postby harivallabhshukla » Tue Jul 16, 2013 3:08 am

how php compare two dateTime object with comparator operator
$date1=new DateTime("07-03-2010");
$date2=new Datetime("21-09-2015");
if($date2>$date1)
{
echo "two datetime object has compared";
}
harivallabhshukla
New php-forum User
New php-forum User
 
Posts: 5
Joined: Tue Jul 16, 2013 2:54 am

Re: how php compare two DateTime object

Postby johnj » Wed Jul 17, 2013 8:08 pm

The DateTime class has a method called diff(). Use that to compare dates
example:
Code: Select all
$interval = $date1->diff($date2);
echo $interval->format('%R%a days');


if the $interval is a positive value than $date1 is greater than $date2.
johnj
php-forum Super User
php-forum Super User
 
Posts: 1805
Joined: Thu Mar 10, 2011 5:07 pm

Re: how php compare two DateTime object

Postby harivallabhshukla » Fri Jul 19, 2013 4:31 am

when i use comparator operator then also it give correct result
i.e Below code give correct result


if($date2>$date1)
{
echo "date2 is greater than date1";
}


BUT WHY?
harivallabhshukla
New php-forum User
New php-forum User
 
Posts: 5
Joined: Tue Jul 16, 2013 2:54 am

Re: how php compare two DateTime object

Postby johnj » Fri Jul 19, 2013 5:36 am

check the php manual, based on php version, there are some changes to this class.
johnj
php-forum Super User
php-forum Super User
 
Posts: 1805
Joined: Thu Mar 10, 2011 5:07 pm

Re: how php compare two DateTime object

Postby harivallabhshukla » Fri Jul 19, 2013 5:51 am

can you give me link where i can get this information.Thanks in advance
harivallabhshukla
New php-forum User
New php-forum User
 
Posts: 5
Joined: Tue Jul 16, 2013 2:54 am

Re: how php compare two DateTime object

Postby johnj » Sat Jul 20, 2013 12:39 am

If your version of php allowes to compare the class instances ($date1 and $date2) then please go ahead and follow that route.
http://www.php.net/manual/en/datetime.construct.php
johnj
php-forum Super User
php-forum Super User
 
Posts: 1805
Joined: Thu Mar 10, 2011 5:07 pm


Return to PHP General

Who is online

Users browsing this forum: landi and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron