Slimshadddyyy
Slimshadddyyy

Reputation: 4081

PHP - Compare Dates with different format

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';

Upvotes: 3

Views: 4527

Answers (6)

jettech01
jettech01

Reputation: 1

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.

Upvotes: -1

Saty
Saty

Reputation: 22532

Use strtotime():

<?php

    $date1 = strtotime("16-MAR-2015");
    $date2 = strtotime("04-FEB-15");

?>

and compair

Upvotes: 5

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38552

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);

Upvotes: 3

Ghostman
Ghostman

Reputation: 6114

$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()

Upvotes: 0

EternalHour
EternalHour

Reputation: 8661

First, you need to turn them into a DateTime object.

DEMO

$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.

Upvotes: 0

Cl&#233;ment Malet
Cl&#233;ment Malet

Reputation: 5090

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
}

Upvotes: 0

Related Questions