Current Location: Home> Latest Articles> gmdate How to use zero-complement when formatting dates

gmdate How to use zero-complement when formatting dates

gitbox 2025-05-29

In PHP, the gmdate() function is used to format a date and time string based on Greenwich Standard Time (GMT). Unlike the date() function, gmdate() returns GMT time, not server local time. It is perfect for handling date-time requirements across time zones.

When formatting dates with gmdate() , you often encounter "zero-compensation" problems, such as hours, minutes, seconds, months and dates. If the number is less than 10, should you fill in zero? In fact, gmdate() provides formatting characters to automatically handle this.

1. Common format characters and zero-complement situations

  • d ——Represents the day of the month, with zero compensation, range from 01 to 31

  • j ——Date without zero compensation, range is 1 to 31

  • m —— Represents month, with zero compensation, range from 01 to 12

  • n —— Months without zero-compensation, range from 1 to 12

  • H —— 24-hour system with zero compensation, range is 00 to 23

  • G —— 24-hour system, without zero compensation, range is 0 to 23

  • i —— Minutes, with zero compensation, range is 00 to 59

  • s - seconds, with zero compensation, range is 00 to 59

So, as long as you want to automatically fill zeros, use format characters with fill zeros, such as d , m , H , i , s . If you do not want to make up the zero, use the corresponding character without the zero complement.

2. Sample code

 <?php
// Current timestamp
$timestamp = time();

// Date and time with zero-complement format
echo gmdate('Y-m-d H:i:s', $timestamp);
// Output example: 2025-05-24 14:05:09

// Date and time without zero replenishment
echo gmdate('Y-n-j G:i:s', $timestamp);
// Output example: 2025-5-24 14:5:9
?>

The above code shows that gmdate() automatically decides whether to fill zero based on the format character itself, and we do not need additional processing.

3. Manual zero-compensation is not recommended

Some newbies may try to use conditional statements to determine the size of numbers and then make up for zeros, such as:

 <?php
$hour = gmdate('G');
if ($hour < 10) {
    $hour = '0' . $hour;
}
echo $hour;
?>

This type of writing is cumbersome and prone to errors. It is completely unnecessary, because using the format character H can automatically make up for zeros.

4. Conclusion

  • When formatting dates using gmdate() , you can automatically fill zeros with format characters with zeros without manual operation.

  • For example, d , m , H , i , s will automatically make up for zero.

  • Use j , n , G and other format characters without zero-complement.

5. Reference link

For more formatted characters and usage of gmdate() , you can refer to the official documentation:

https://gitbox.net/manual/en/function.gmdate.php