How to work with Date and Time in PHP

Format date

We can use the function date() which accepts the date format and timestamp as arguments.

Syntax

date(format,timestamp)

Datetime format

Here are some common characters for dates:

  • d: day(01 to 31)
  • m: month (01 to 12)
  • Y: year (in four digits)
  • l (lowercase ‘L’): day of the week

Common characters for time:

  • H - 24-hour format of an hour (00 to 23)
  • h - 12-hour format of an hour with leading zeros (01 to 12)
  • g - 12-hour format of an hour without leading zeros
  • i - Minutes with leading zeros (00 to 59)
  • s - Seconds with leading zeros (00 to 59)
  • a - Lowercase am or pm
echo date("d/m/Y g:ia"); // 16/11/2022 9:22am

You can check more PHP datetime format here.

Check current timezone

We can echo out the current timezone with the function date_default_timezone_get()

echo date_default_timezone_get(); // Europe/Berlin

Work with different timezone

We can config the timezone using the function date_default_timezone_set() and pass in the valid timezone.

Here is the list of supported timezones.

date_default_timezone_set("Asia/Tokyo");
date_default_timezone_set("UTC");

Convert string to timestamp

We can convert textual datetime into unit timestamp using strtotime() function.

echo date("d/m/Y g:ia", strtotime("next Monday")); // 21/11/2022 12:00am

You can check the relative format here.