简体   繁体   中英

How to convert the date into paticular format using PHP?


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('Ym-d',strtotime($birthdate)); echo $date; ?> <? $birthdate="08-13-2000"; $date=date('Ym-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.

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

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 ...

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