PHP – Date Formatting and strtotime()

Here are some examples of date formatting in PHP.

<?php
  /* Today is 2011-01-15T09:43:14+00:00 */

  /* Common date formats*/
  // ISO 8601 format
  print date("c")."<br/>";
  // January 15, 2011, 9:43am
  print date("F j, Y, g:ia")."<br/>";
  // 01.15.11
  print date("m.d.y")."<br/>";
  // 2011 Jan 15th
  print date("Y M jS")."<br/>";
  // 15, 1, 2011 
  print date("j, n, Y")."<br/>";
  // 09:43:14
  print date("H:i:s")."<br/>";
  // 20110115
  print date("Ymd")."<br/>";
  // 20110117
  print date("Ymd", strtotime("2 day"))."<br/>";
  // 20101215
  print date("Ymd", strtotime("-1 month"))."<br/>";
  
  /* Set default time zone */
  /* Hong Kong */
  date_default_timezone_set("Asia/Hong_Kong");
  // 2011-01-15T17:43:14+08:00
  print date("c")."<br/>";
  
  /* Create a date for Athens time zone */
  $timezone = new DateTimeZone("Europe/Athens");
  $date = new DateTime();
  $date->setTimezone($timezone);
  // 2011-01-15T11:43:14+02:00
  print $date->format("c")."<br/>";
?>

 

Done =)

Reference:

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.