tags:

views:

45

answers:

2

Hi Friends,
I am having the input box for getting the value in mm-dd-yyyy format.So When I get the date I try to covert it into YYYY-MM-DD format.But It doesnt work.
For Example :
<? $birthdate="08-13-2000"; $date=date('Y-m-d',strtotime($birthdate)); echo $date; ?>. Output is 1970-01-01.
But If I gave 13-08-2000 I got 2000-08-13.I dont want to split.Because in my application I used in manyplaces like this.But I think the strtotime convert it into unix timestamp format even whatever the value.That's why I am try to do like.What's wrong I am understanding or doing?
Thanks in advance.

+3  A: 

Hello,

Try this:

$date = explode("-", "08-13-2000"); // input MM-DD-YYYY
$time = mktime(0, 0, 0, $date[0], $date[1], $date[2]); // to time
$date = date('Y-m-d', $time); // transform to Y-m-d
echo $date; // output YYYY-MM-DD
  • $date[0] is the month
  • $date[1] is the day
  • $date[2] is the year

And if you use it in manyplaces, make a function():

function transformDate($input)
{
    $date = explode("-", $input);
    $time = mktime(0, 0, 0, $date[0], $date[1], $date[2]);
    $date = date('Y-m-d', $time);

    return $date;
}

echo transformDate("08-13-2000");
Isern Palaus
I think explode ("-", "08-13-2000") would work a lot better.
lonesomeday
Wouldn't you want explode('-','08-13-2000'); ?
ASpencer
True, my fault, editing! :)
Isern Palaus
+1 (despite the typo!) because this is much more reliable than trusting on the vagaries of strtotime.
lonesomeday
@lonesomeday I agree, though it was interesting to discover some of strtotime's more... interesting vagueries.
ASpencer
+3  A: 

strtotime() parses dash-separated dates as dd-mm-yyyy. You'll need to input birthdate as "08/13/2000". str_replace should do the job for that if you can't change the expected seperator for the input.

credit for the separator differences to sam at frontiermedia dot net dot au from php.net

Edit: Have some sample code for if you need to do the replace:

$birthdate = '08-13-2000';
$birthdate = str_replace('-','/',$birthdate);
$date      = date('Y-m-d',strtotime($birthdate)); 

echo $date;

Otherwise it'd just be

$birthdate = '08/13/2000';
... snip ...
ASpencer