Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Date and Time in PHP

Overview

Working with dates and times is a common requirement in PHP development. PHP provides a robust set of tools and functions to handle dates and times, allowing you to perform various operations like formatting, calculating differences, and more.

Getting the Current Date and Time

PHP's date() function is used to format a local date and time. It returns a string formatted according to the given format string using the current time.

Example:

echo date('Y-m-d H:i:s');

Formatting Dates

The date() function allows you to format dates in various ways. Here are some common formatting characters:

  • Y: A full numeric representation of a year, 4 digits
  • m: Numeric representation of a month, with leading zeros
  • d: Day of the month, 2 digits with leading zeros
  • H: 24-hour format of an hour with leading zeros
  • i: Minutes with leading zeros
  • s: Seconds with leading zeros

Example:

echo date('l, F j, Y');

Using Timestamps

A timestamp is the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). You can get the current timestamp using the time() function.

Example:

echo time();

You can also convert a timestamp into a readable date using the date() function:

Example:

echo date('Y-m-d H:i:s', 1609459200);  // Timestamp for 2021-01-01 00:00:00

Calculating Date Differences

PHP provides the DateTime class which makes it easy to perform date arithmetic. You can calculate the difference between two dates using the diff method.

Example:

$datetime1 = new DateTime('2021-01-01');
$datetime2 = new DateTime('2021-12-31');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
                
diff($datetime2); echo $interval->format('%R%a days'); ?>

Working with Time Zones

By default, PHP uses the server's time zone settings. You can set the default time zone using the date_default_timezone_set() function.

Example:

date_default_timezone_set('America/New_York');
echo date('Y-m-d H:i:s');
                

You can also work with different time zones using the DateTimeZone class.

Example:

$datetime = new DateTime('now', new DateTimeZone('Europe/London'));
echo $datetime->format('Y-m-d H:i:s');
                
format('Y-m-d H:i:s'); ?>