开发者

How to format datetime most easily in PHP?

开发者 https://www.devze.com 2022-12-14 03:59 出处:网络
To change 2009-12-09 13:3开发者_如何学JAVA2:15 to 09/12/2009here: echo date(\"d/m/Y\", strtotime(\'2009-12-09 13:32:15\'))

To change 2009-12-09 13:3开发者_如何学JAVA2:15 to 09/12/2009


here:

 echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))


You can use strtotime to get the timestamp of the first date, and date to convert it to a string using the format you want.

$timestamp = strtotime('2009-12-09 13:32:15');
echo date('d/m/Y', $timestamp);

And you'll get :

09/12/2009



[edit 2012-05-19] Note that strtotime() suffers a couple of possibly important limitations:

  • The format of the date must be YYYY-MM-DD; it might work in some other cases, but not always !
  • Also, working with UNIX Timestamps, as done with date() and strtotime() means you'll only be able to work with dates between 1970 and 2038 (possibly a wider range, depending on your system -- but not and illimited one anyway)

Working with the DateTime class is often a far better alternative:

  • You can use either DateTime::__construct() or DateTime::createFromFormat() to create a DateTime object -- the second one is only available with PHP >= 5.3, but allows you to specify the date's format, which can prove useful,
  • And you can use the DateTime::format() method to convert that object to any date format you might want to work with.


Using the date() method.

print date("d/m/Y", strtotime("2009-12-09 13:32:15"));


 $long_date = '2009-12-09 13:32:15';

 $epoch_date = strtotime($long_date);

 $short_date = date('m/d/Y', $epoch_date);

The above is not the shortest way of doing it, but having the long date as an epoch timestamp ensures that you can reuse the original long date to get other date format outputs, like if you wanted to go back and have just the time somewhere else.

0

精彩评论

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