Matt Jameson
Matt Jameson

Reputation: 582

PHP date year format

I am having problems with dates in php- sometimes the date gets to us in d/m/y and other times its d/m/Y. I want to convert all dates to d/m/Y.

Working with my current dataset, how would I get 24/06/2015 from 24/06/15 using php?

So far I have tried :

$original_date = '24/06/15';

$new_date = date('d/m/Y', strtotime($original_date));

This brings back 01/01/1970

Upvotes: 1

Views: 2220

Answers (4)

dblack
dblack

Reputation: 113

The problem is that the strtotime doesn't recognise the UK date format, so convert the format first then format the date.

Try this:

$original_date = "24/06/15"; 
list($date,$month,$year) = sscanf($original_date, "%d/%d/%d");
$date_convert = $year."-".$month."-".$date;
$new_date = date("d/m/Y", strtotime($date_convert));
echo $new_date;

Upvotes: 0

Ashish Choudhary
Ashish Choudhary

Reputation: 2034

Its wrong format of date you are using for strtotime.

Have a look at Date Formats

The correct code should have

$original_date = '15/06/24'; // Notice : its mm/dd/yy here

$new_date = date('d/m/Y', strtotime($original_date));

Upvotes: -1

JGCW
JGCW

Reputation: 1529

use the lowercase 'y'. See the PHP date manual.

$new_date = date('d/m/y', strtotime($original_date));

y = A two digit representation of a year

Upvotes: 0

deceze
deceze

Reputation: 521994

This is probably the most robust method:

$string = '24/06/15';
$date = DateTime::createFromFormat('d/m/y', $string) ?: DateTime::createFromFormat('d/m/Y', $string);
echo $date->format('d/m/Y');

createFromFormat returns false if you try to parse 24/06/2014 using the d/m/y format, so in that case you just retry with d/m/Y. You then get a DateTime object which you can format and output any way you like.

Upvotes: 3

Related Questions