开发者

How to convert the date into paticular format using PHP?

开发者 https://www.devze.com 2023-01-19 09:19 出处:网络
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.

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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消