简体   繁体   中英

Date conversion in php 1970-01-01

Hi all I am using date conversion as bellow

$startdate='12/10/2012'; 
$newstartdate = date('Y-m-d',strtotime($startdate));

some time it works but some time it shows 1970-01-01

Example: 12/10/2012 works 13/10/2012 does not works shows 1970-01-01

See PHP's date and time formats page .

If you use / characters to delimit your date, it treats it as mm/dd/yy . Years only have 12 months.

For dates in a sensible order, use hyphen characters.

$startdate='12-10-2012';
$newstartdate = date('Y-m-d',strtotime($startdate));

Use DateTime::createFromFormat to specify the date format.

$date = DateTime::createFromFormat('d/m/Y', '13/10/2012');
echo $date->format('Y-m-d');

From the manual : The function expects to be given a string containing an English date format...

The date 13/10/2012 in "English" (the documentation is wrong about this; it should say "US American") format means the tenth day of the thirteenth month. The thirteenth month doesn't exist in the Gregorian calendar and hence strtotime gives a failure result 0, which if used as a Unix timestamp, converts to 1970-01-01.

Use strftime to handle differently formatted dates.

这可能是因为PHP假设“ 12/10/2012”为2012年12月10日(可以),而“ 13/10/2012”为未定义月份的10日,因此无法正确计算。

The following code may help. It replaces / with - :

$startdate='12/10/2012'; 
$date1 = strtr($startdate, '/', '-');
echo date('Y-m-d', strtotime($date1));

Follow the above mentioned date class and links to render the output, however if you still stuck with the usage try doing it in this way (just a learning method to look into more in PHP, however this is very bad piece of code :P )

$startdate1='13/10/2012'; 
$myarr = explode('/',$startdate1);

$mynewdate = $myarr[1].'/'.$myarr[0].'/'.$myarr[2];

$newstartdate1 = date('Y-m-d',strtotime($mynewdate));

echo $newstartdate1;

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