简体   繁体   中英

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

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.

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

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM