Current Location: Home> Latest Articles> PHP strftime() Function Guide: Date and Time Formatting Explained

PHP strftime() Function Guide: Date and Time Formatting Explained

gitbox 2025-06-18

1. Introduction

In PHP, the strftime() function is used to format dates and times. It takes two parameters: a format string and an optional timestamp. Based on the provided format, strftime() returns a formatted date and time string. The format string includes special conversion specifiers that start with the percentage symbol (%).

2. Conversion Specifiers

Conversion specifiers are used to define how the date and time should be formatted. Some common conversion specifiers are:

  • %a - Abbreviated weekday name (e.g., Sun to Sat)
  • %A - Full weekday name (e.g., Sunday to Saturday)
  • %d - Day of the month (01 to 31)
  • %m - Month (01 to 12)
  • %Y - Full year (e.g., 2022)
  • %H - Hour (00 to 23)
  • %M - Minute (00 to 59)
  • %S - Second (00 to 59)
  • %Z - Timezone abbreviation (e.g., EST, PDT)

For more conversion specifiers, you can refer to the official PHP documentation.

3. Example Usage

Here is an example of how to use the strftime() function to get the current time:


$timestamp = time();
$date = strftime("%Y-%m-%d %H:%M:%S", $timestamp);
echo $date;
        

The above code will output the current time in the format "Year-Month-Day Hour:Minute:Second".

If you want to get a localized version of the date and time, you can use strftime() in combination with the setlocale() function. For example, the following code will output the time in a Chinese format:


setlocale(LC_ALL, "zh_CN.utf-8");
$timestamp = time();
$date = strftime("%Y年%m月%d日 %A %X", $timestamp);
echo $date;
        

This code will output the localized date and time, such as "2025年06月19日 星期四 14:30:45".

4. Important Considerations

When using strftime(), you might encounter incorrect date formatting due to an improper system locale setting. You can adjust the locale using the setlocale() function. For example, to set the locale to American English, use the following code:


setlocale(LC_ALL, "en_US.utf-8");
        

Note that the behavior of strftime() may differ across operating systems, as it depends on the system's C library.

5. Conclusion

The strftime() function is a powerful tool in PHP for formatting dates and times. Whether you need to output standard formats or generate localized dates and times, strftime() offers robust support. Be sure to properly set the locale to avoid formatting issues.