Dharmalingam Arumugam
Dharmalingam Arumugam

Reputation: 407

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

Upvotes: 0

Views: 5454

Answers (6)

basil
basil

Reputation: 21

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

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

Upvotes: 0

swapnesh
swapnesh

Reputation: 26732

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;

Upvotes: -1

Bart Friederichs
Bart Friederichs

Reputation: 33533

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.

Upvotes: 1

Paul
Paul

Reputation: 9012

This is probably because PHP assumes "12/10/2012" to be the 10th of December 2012 (which is fine) and "13/10/2012" would be the 10th of an undefined month, hence it can't calculate it properly.

Upvotes: 1

xdazz
xdazz

Reputation: 160883

Use DateTime::createFromFormat to specify the date format.

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

Upvotes: 2

Quentin
Quentin

Reputation: 944021

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

Upvotes: 5

Related Questions