The date Function

The date function outputs the date in a specified format. The first parameter of the function is the format, and the second optional parameter is a point in time in timestamp format. If the second parameter is not specified, the current time is taken; if specified, the given time is used.

The format is specified using control commands (English letters), and any separators can be inserted between them (hyphens, colons, and so on).

The function accepts the following commands (uppercase letters differ from lowercase ones, pay attention):

Syntax

phpdate(string $format, ?int $timestamp = null): string

Examples of Using date

php<?php
  // All examples are shown for the date 01.06.2013 at 12.23.59, Monday
  
  echo date('Y'); // outputs '2013'
  echo date('y'); // outputs '13'
  echo date('m'); // outputs '06' - month number
  echo date('d'); // outputs '01' - day of the month
  echo date('j'); // outputs '1'  - day of the month (without leading zero)
  echo date('w'); // outputs '1'  - Monday
  echo date('H'); // outputs '12' - hours
  echo date('i'); // outputs '23' - minutes
  echo date('s'); // outputs '59' - seconds
  
  echo date('d-m-Y'); // outputs '01-06-2013'
  echo date('d.m.Y'); // outputs '01.06.2013'
  echo date('H:i:s d.m.Y'); // outputs '12:23:59 01.06.2013'
?>

The Second Parameter of the date Function

The date function has a second optional parameter, which accepts a point in time in timestamp format. If you pass this parameter, the date function will format not the current time, but the one passed as the second parameter. This timestamp can be obtained, for example, via mktime (but not necessarily):

php<?php
  echo date('d-m-Y', mktime(0, 0, 0, 12, 29, 13)); // outputs '29-12-2013'
?>

This can be used to find out the day of the week for a specific date - simply pass it as the second parameter using the mktime function, and use the control character 'w' as the first parameter:

php<?php
  // Let's find out what day of the week was 29-12-2013:
  echo date('w', mktime(0, 0, 0, 12, 29, 13)); // outputs '0' - Sunday
?>

See Also

  • the mktime function,
    which returns a point in time in timestamp format