Dates and times can be important elements in a web database application. PHP has the capability to recognize dates and times and handle them differently than plain character strings. Dates and times are stored by the computer in a format called a timestamp.

PHP converts dates from your notation into a timestamp that the computer understands and from a timestamp into a format familiar to people. PHP handles dates and times with built-in functions.

Formatting Date

The function that you will use most often is date, which converts a date or time from the timestamp format into a format that you specify. The general format is

$mydate = date("format",$timestamp);

If $timestamp isn’t included, the current time is obtained from the operating system and used. Thus, you can get today’s date with the following:

$today = date("Y/m/d");

The format is a string that specifies the date format that you want stored in the variable. The parts of the date can be separated by a hyphen (-), a dot (.), a forward slash (/), or a space.

  • F: Month in text, not abbreviated (January)
  • M: Month in text, abbreviated (Jan)
  • m: Month in numbers with leading zeros (02, 12)
  • n: Month in numbers without leading zeros (1, 12)
  • d: Day of the month; two digits with leading zeros (01, 14)
  • j: Day of the month without leading zeros (3, 30)
  • l: Day of the week in text, not abbreviated (Friday)
  • D: Day of the week in text, abbreviated (Fri)
  • w: Day of the week in numbers From 0 (Sunday) to 6 (Saturday)
  • Y: Year in four digits (2015)
  • y: Year in two digits (02)
  • g: Hour between 0 and 12 without leading zeros (2, 10)
  • G: Hour between 0 and 24 without leading zeros (2, 15)
  • h: Hour between 0 and 12 with leading zeros (01, 10)
  • H: Hour between 0 and 24 with leading zeros (00, 23)
  • i: Minutes (00, 59)
  • s: Seconds (00, 59)
  • a: am or pm in lowercase (am, pm)
  • A: AM or PM in uppercase (AM, PM)

Storing a Timestamp

You can assign a timestamp with the current date and time to a variable with the following statement:

$today = time();

Another way to store a current timestamp is with the statement:

$today = strtotime(“today”);