How to easily format datetime in PHP?

To change 2009-12-09 13:32:15 to 2009-12-09 13:32:15

+6
php time
source share
4 answers

here:

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

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 will get:

 09/12/2009 



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

  • The date format must be YYYY-MM-DD ; it may work in some other cases, but not always!
  • In addition, working with UNIX timestamps , as with date() and strtotime() ll, will only be able to work with dates between 1970 and 2038 (possibly in a wider range, depending on your system, but anyway and without illustrations).

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

+4
source share

Using the date() method.

 print date("d/m/Y", strtotime("2009-12-09 13:32:15")); 
0
source share
  $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 to do this, but a long date as a timestamp of an era ensures that you can reuse the original long date to get other date format output, for example if you want to return and only have time elsewhere.

0
source share

All Articles