Current Location: Home> Latest Articles> How to implement custom date and time format through gmdate

How to implement custom date and time format through gmdate

gitbox 2025-05-26

In PHP, the gmdate function is a very practical date-time processing tool that returns formatted date and time strings based on Greenwich Standard Time (GMT). Compared with the date function, gmdate is not affected by the server time zone settings and is more suitable for scenarios that require unified time standards, such as logging, cross-time zone time display, etc.

This article will introduce how to use the gmdate function to customize the date and time format you want.

1. gmdate function basics

The basic syntax of gmdate is as follows:

 gmdate(string $format, int|null $timestamp = null): string
  • $format : date and time format, the format rules are the same as the date function.

  • $timestamp : timestamp, default to the current time.

2. Common date and time format symbols

Format characters meaning example
Y Four-digit years 2025
m Double-digit months 05
d Double digit day twenty four
H 24-hour hours 14
i minute 30
s Second 45
D Abbreviation of the week (English) Sat

For more formatting characters, please refer to the official PHP documentation.

3. Custom date and time output through gmdate

Suppose you want to output a time similar to the following format:

 2025-05-24 14:30:45

Code example:

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

If you want to output a more personalized format, for example:

 Saturday, 24th of May 2025, 14:30 GMT

You can write this way:

 echo gmdate('l, jS \of F Y, H:i \G\M\T');

Escape characters \ are used here to avoid the letters being interpreted as format characters.

4. Use timestamp parameters

You can also pass in a timestamp to format a specific time. For example:

 $timestamp = strtotime('2023-01-01 00:00:00');
echo gmdate('Y-m-d H:i:s', $timestamp);

5. Example: Combining URL to output the current GMT time

Suppose you need to generate a URL with time parameters, such as visiting https://gitbox.net/api?time=current GMT time , the code is as follows:

 $time = gmdate('Y-m-d\TH:i:s\Z');
$url = "https://gitbox.net/api?time=" . urlencode($time);
echo $url;

Here ISO 8601 format is used to output GMT time and escape through urlencode to safely put URL parameters.