PHP Date and Time

By Shahnail Khan Last updated : December 22, 2023

While working on web development projects, you make sure to add all the elements to your website. One of the crucial elements is inserting date and time, and PHP provides a set of functions to handle these operations. This tutorial will guide you through the basics of working with date and time in PHP, helping you understand key functions and their usage.

Getting Started with Date and Time in PHP

  • To get and format date and time in PHP: Use the date() function.
  • To set the time zone: Use the date_default_timezone_set() function.

PHP date() Function

The main function for handling dates in PHP is date() which allows you to format and display the current date or a specific date according to your requirements.

Syntax

The basic syntax of the date() function is:

string date (string $format, int $timestamp = time ())

Parameters

As you can see this function accepts two parameters.

  • $format (required): Specifies the format of the date, which will be displayed on the browser. It consists of various format characters representing different parts of the date and time. Here are some commonly used format characters:
    • Y: Four-digit year (e.g., 2023)
    • m: Two-digit month (01 through 12)
    • d: Two-digit day of the month (01 through 31)
    • H: Two-digit hour in 24-hour format (00 through 23)
    • i: Two-digit minutes (00 through 59)
    • s: Two-digit seconds (00 through 59)
  • $timestamp (optional): This is the specific time you want to show. If you don't give any time, it'll use the current time.

Example: Get the Current Date & Time in PHP

For example, if you want to display the current date and time as "YYYY-MM-DD HH:MM:SS," you would use the following format string:

<?php
echo date("Y-m-d H:i:s");
?>

Output

2023-12-22 22:29:08

Setting Timezone in PHP

To ensure accurate time representation, it's a must to set the timezone. The date_default_timezone_set() function is used for this purpose.

Time Zones

Let's have a look at some timezone names that you can use with the date_default_timezone_set() function in PHP:

  1. UTC (Coordinated Universal Time):
    • UTC
  2. United States:
    • Eastern Time (New York): America/New_York
    • Central Time (Chicago): America/Chicago
    • Mountain Time (Denver): America/Denver
    • Pacific Time (Los Angeles): America/Los_Angeles
  3. United Kingdom:
    • Europe/London
  4. Asia:
    • Tokyo, Japan: Asia/Tokyo
    • Beijing, China: Asia/Shanghai
  5. Australia:
    • Sydney: Australia/Sydney
    • Melbourne: Australia/Melbourne
  6. Europe:
    • Berlin, Germany: Europe/Berlin
    • Paris, France: Europe/Paris
  7. India:
    • Asia/Kolkata

Click here to learn more timezones supported by PHP.

Setting and Displaying Date with Timezone

In this example, the timezone is set to 'America/New_York,' and the time is displayed using the format "H:i:s" (hour:minute: second).

<?php
date_default_timezone_set("America/New_York");

echo "Current time in New York: " . date("H:i:s");
?>

Output

Current time in New York: 17:42:02

PHP strtotime() Function: Create Date From a String

The strtotime() function is powerful for parsing date strings into Unix timestamps. It converts human-readable dates to a format that PHP can understand.

Example: Using strtotime() to Calculate Future Date

<?php
$futureDate = strtotime("+1 week");
echo "One week from now: " . date("Y-m-d", $futureDate);
?>

Output

One week from now: 2023-12-29

In this example, the strtotime() function calculates the timestamp for one week into the future, and the date() function formats and displays it.

PHP mktime() function: Generate a Unix Timestamp for a Date and Time

The mktime() function in PHP is used to generate a Unix timestamp for a specific date and time.

Syntax

The syntax of mktime() function is :

mktime(hour, minute, second, month, day, year)

Example: Create a date with mktime()

Let's take an example to understand this function better.

<?php
// Create a timestamp for December 25, 2023, 12:00:00 PM
$timestamp = mktime(12, 0, 0, 12, 25, 2023);

// Display the timestamp
echo "Timestamp for December 25, 2023, 12:00:00 PM: $timestamp";
?>

Output

Timestamp for December 25, 2023, 12:00:00 PM: 1703505600

In this example, mktime() is used to create a timestamp for December 25, 2023, at 12:00:00 PM. The resulting timestamp is then displayed.

PHP Date and Time: Examples

Let's take some common PHP date and time examples with solutions and explanations.

Example 1: Display the current date and time in PHP

The date("Y-m-d H:i:s") formats the current date and time as Year-Month-Day Hour:Minute:Second.

<?php
echo "Current date and time: " . date("Y-m-d H:i:s");
?>

Example 2: Format a specific date in PHP

The strtotime($specificDate) converts the date string to a Unix timestamp, and the date("l, F j, Y", $timestamp) formats the timestamp in a user-friendly way.

<?php
$specificDate = "2023-06-15";
$formattedDate = date("l, F j, Y", strtotime($specificDate));
echo "Formatted date: " . $formattedDate;
?>

Example 3: Calculate the difference between two dates in PHP

The strtotime($startDate) and strtotime($endDate) convert the dates to timestamps. The difference in seconds is calculated and then converted to days.

<?php
$startDate = "2023-01-01";
$endDate = "2023-12-31";

$startTimestamp = strtotime($startDate);
$endTimestamp = strtotime($endDate);

$differenceInSeconds = $endTimestamp - $startTimestamp;
$differenceInDays = $differenceInSeconds / (60 * 60 * 24);

echo "Difference in days: " . $differenceInDays;
?>

Example 4: Add or subtract days from a given date in PHP

The strtotime($originalDate . " +$daysToAdd days") adds the specified number of days to the original date.

<?php
$originalDate = "2023-04-10";
$daysToAdd = 7;

$newDate = date("Y-m-d", strtotime($originalDate . " +$daysToAdd days"));
echo "New date after adding $daysToAdd days: " . $newDate;
?>

Example 5: Get the day of the week for a specific date in PHP

The date("l", strtotime($specificDate)) returns the day of the week for the given date.

<?php
$specificDate = "2023-09-20";
$dayOfWeek = date("l", strtotime($specificDate));
echo "Day of the week: " . $dayOfWeek;
?>

Useful Web References

These references might be helpful for you:

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.