Date Format:
$date1 = '16-MAR-2015';
$date2 = '04-FEB-15';
How can I check if
$date1 <= $date2 || $date1 => $date2
Do I need to convert date format in
$date1 = '16-3-2015';
$date2 = '04-2-15';
Try this way, it works. DEMO
$date1 = DateTime::createFromFormat('j-M-Y', '16-MAR-2015');
$date2 = DateTime::createFromFormat('j-M-y', '04-FEB-15');
$date1=$date1->format('Y-m-d');
$date2=$date2->format('Y-m-d');
var_dump($date1 <= $date2);
var_dump($date1 >= $date2);
You don't need to convert anything with the given formats, DateTime will do what you need.
Just turn them into DateTime objects and compare them :
$date1 = '16-MAR-2015';
$date2 = '04-FEB-15';
$date1 = date_create($date1);
$date2 = date_create($date2);
// $date1 > $date2 -> true
// $date1 < $date2 -> false
Or
if (date_create($date1) > date_create($date2)) {
// Use $date1 unchanged
}
Catchable fatal error: Object of class DateTime could not be converted to string16-MAR-2015 is comparable to 04-FEB-15 (see year format) using date_create()?$date1 somewhere else. Use a temporary variable to do your comparisons such as $tmpDate1. Comparisons on DateTime objects is not what throw the fatal error. Not sure I understand what you mean, but yes you could use if (date_create($date1) > date_create($date2)) {$date1 is defined once only. Not used anywhereFirst, you need to turn them into a DateTime object.
$date1 = '16-MAR-2015';
$date2 = '04-FEB-15';
$dateComp1 = new DateTime($date1);
$dateComp2 = new DateTime($date2);
Then you can compare them, DateTime is smart enough to convert the format automatically.
Catchable fatal error: Object of class DateTime could not be converted to string $date1 and $date1 for the DateTime objects. You won't be able to echo or manipulate them once they are converted.DateTime and not strtotime ? Many roads lead to Rome. And what about DateTime::createFromFormat('j-M-Y', '16-MAR-2015'); ?$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString); $newDateString = $myDateTime->format('m/d/Y'); There is a magical function called strtotime()
If you need to print the value in a readable format you can use the function DATE
date("d-m-Y h:i:s",$date1);
In your case. You want to use
Date.parse()
$date1 = '16-MAR-2015' and $date2 = '04-FEB-15'; ?date("d-m-Y h:i:s",$date1);try
date1= new DateTime();
date1= new Datetime->format('d-m-Y'); // this will print year 4 digits ie; 2017
date2= new DateTime();
date2= new DateTime->format('d-m-y'); //this will print 2 digit year ie; 17
// to compare
$differance=$date1->diff($date2);
echo $differance->format('d-m-y'); //or change to upper case Y for 4 digit year
note... in mysql 5.6 it seems the input format must be Y first: if you insert it with Y-first format first, it seems to compare correctly no matter what the second format is.
$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString); $newDateString = $myDateTime->format('m/d/Y');There is a magical function calledstrtotime()