Date and time formatting in PHP
When developing a website, you often need to work with dates and times. For example, you might want to display the date a post was last modified or mention when a reader left a comment. You may also want to display a countdown until a special event occurs.
Fortunately, PHP comes with some built-in date and time functions that will help us do all this easily.
This tutorial will teach you how to format the current date and time in PHP. You will also learn how to get a timestamp from a date string and how to add and subtract different dates.
Get the date and time in string format
date($format, $timestamp)
is one of the most commonly used date and time functions in PHP. It takes the desired date output format as the first argument and an integer as the timestamp value that needs to be converted to the given date format. The second parameter is optional, omitting it will output the current date and time in string format based on the value of $format
.
$format
The parameter accepts a range of characters as valid values. Some of these characters have simple meanings: Y
gives you the full numeric representation of the 4-digit year (2018), while y
only gives you the last two digits of the year (this year) 18). Likewise, H
will display the hour in 24-hour format with leading zeros, but h
will display the hour in 12-hour format with leading zeros.
The following are some of the most common date format characters and their values.
character | meaning | Example |
---|---|---|
D |
Day of the month (with leading zeros) | 03 or 17 |
j |
Day of the month without leading zero | 3 or 17 |
D |
Day of the week represented by three-letter abbreviation | on Monday |
l |
Day of the week | Monday |
M |
The month is a number with leading zeros | 09 or 12 |
n |
The month is a number without leading zeros | 9 or 12 |
M |
Month as three-letter abbreviation | September |
F |
Whole month | September |
Y |
Double-digit year | 18 |
Y |
annual | 2018 |
There are many other special characters that can be used to specify the output of the date()
function. It is best to consult the format character table in the date()
function documentation for more information about special cases.
Now let's look at some practical examples of the date()
function. We can use it to get the current year, current month, current hour, etc. We can also use it to get the complete date string.
<?php // Output — 2018 echo date('Y'); // Output — September 2018 echo date('F Y'); // Output — 13 September, 2018 echo date('d F, Y'); // Output — 13 September, 2018 (Thursday) echo date('d F, Y (l)');
You can also use the date()
function to output the time. Here are some of the most commonly used time format characters:
character | meaning | Example |
---|---|---|
G |
Hour in 12-hour format without leading zeros | 1 or 12 |
H |
Hour in 12-hour format with leading zeros | 01 or 12 |
G |
Hour in 24-hour format without leading zeros | 1 or 13 |
H |
Hour in 24-hour format with leading zeros | 01 or 13 |
A |
am/pm lower case | morning |
A |
am/pm Capitalized | morning |
i |
Minutes with leading zeros | 09 or 15 |
s |
Seconds with leading zeros | 05 or 30 |
这里是一些输出格式化时间字符串的示例。
// Output — 11:03:37 AM echo date('h:i:s A'); // Output — Thursday, 11:04:09 AM echo date('l, h:i:s A'); // Output — 13 September 2018, 11:05:00 AM echo date('d F Y, h:i:s A'); ?>
如果您想在日期字符串中使用这些特殊字符,转义它们也很重要。
<?php // Output — CEST201813am18 1115 Thursday. echo date('Today is l.'); // Output — Today is Thursday. echo date('\T\o\d\a\y \i\s l.'); // Output — Today is Thursday. echo 'Today is '.date('l.'); ?>
获取 Unix 时间戳
有时,您需要在 PHP 中获取当前 Unix 时间戳的值。借助 time()
函数,这非常容易。它返回一个整数值,描述自 1970 年 1 月 1 日午夜 (00:00:00) GMT 以来经过的毫秒数。
您还可以使用此功能来回返回时间。为此,您所要做的就是从 time()
的当前值中减去正确的秒数,然后将结果值更改为所需的日期字符串。以下是两个示例:
<?php $ten_days_later = time() + 10*60*60*24; // Output — It will be Sunday 10 days later. echo 'It will be '.date('l', $ten_days_later).' 10 days later.'; $ten_days_ago = time() - 10*60*60*24; // Output — It was Monday 10 days ago. echo 'It was '.date('l', $ten_days_ago).' 10 days ago.'; ?>
您应该记住的一件重要事情是,time()
返回的时间戳值与时区无关,并且获取自 1970 年 1 月 1 日 00:00:00 UTC 以来的秒数。这意味着在特定时间点,此函数将在美国、欧洲、印度或日本返回相同的值。
获取特定日期的时间戳的另一种方法是使用 mktime($hour, $min, $second, $month, $day, $year)
函数。当省略所有参数时,该函数仅使用当前本地日期和时间来计算时间戳值。此函数还可以与 date()
一起使用来生成有用的日期和时间字符串。
<?php $some_time = mktime(1, 1, 1, 12, 3, 1994); // Output — It was Saturday on 03 December, 1994. echo 'It was '.date('l', $some_time).' on '.date('d F, Y', $some_time).'.'; ?>
基本上,time()
可用于来回返回一段时间,而 mktime()
在您想要前往某个时间点时很有用特定时间点。
将日期时间字符串转换为时间戳
当您想要将字符串格式的不同日期和时间值转换为时间戳时,strtotime($time, [$now = time()])
函数将非常有用。该函数可以将几乎所有类型的日期时间字符串解析为时间戳。
您一定要检查有效的时间格式、日期格式、复合日期时间格式和相对日期时间格式。
使用相对日期时间格式,该函数可以轻松地将常用字符串转换为有效的时间戳值。下面的例子应该可以清楚地说明:
<?php $some_time = strtotime("10 months 15 days 10 hours ago"); // Output — It was Sunday on 29 October, 2017 03:16:46. echo 'It was '.date('l', $some_time).' on '.date('d F, Y h:i:s', $some_time).'.'; $some_time = strtotime("next month"); // Output — It is Saturday on 13 October, 2018 01:18:05. echo 'It is '.date('l', $some_time).' on '.date('d F, Y h:i:s', $some_time).'.'; $some_time = strtotime("third monday"); // Output — Date on the third monday from now will be 01 October, 2018. echo 'Date on the third monday from now will be '.date('d F, Y', $some_time).'.'; $some_time = strtotime("last day of November 2021"); // Output — Last day of November 2021 will be Tuesday. echo 'Last day of November 2021 will be '.date('l', $some_time).'.'; ?>
添加、减去和比较日期
可以在日期中添加或减去特定的时间段。这可以借助 date_add()
和 date_sub()
函数来完成。您还可以使用 date_diff()
函数来减去两个日期并以年、月、日或其他形式输出它们之间的差异。
通常,使用 DateTime
类以面向对象的方式执行任何此类与日期和时间相关的算术比按程序执行更容易。我们将在这里尝试这两种样式,您可以选择您最喜欢的一种。
<?php $present = date_create('now'); $future = date_create('last day of January 2024'); $interval = date_diff($present, $future); // Output — 05 years, 04 months and 17 days echo $interval->format('%Y years, %M months and %d days'); $present = new DateTime('now'); $future = new DateTime('last day of January 2024'); $interval = $present->diff($future); // Output — 05 years, 04 months and 17 days echo $interval->format('%Y years, %M months and %d days'); ?>
使用 DateTime::diff()
时,会从调用 diff()
方法的 DateTime
对象中减去DateTime
对象,该对象传递给 diff()
方法。当您编写过程样式代码时,将从第二个日期参数中减去第一个日期参数。
该函数和方法都返回一个 DateInterval()
对象,表示两个日期之间的差异。可以使用 format()
方法文档中列出的所有字符来格式化此间隔以提供特定输出。
当减去或增加时间间隔时,面向对象风格和过程风格之间的差异变得更加明显。
您可以使用 DateTime()
构造函数实例化新的 DateTime
对象。同样,您可以使用 DateInterval()
构造函数实例化 DateInterval
对象。它接受一个字符串作为其参数。间隔字符串以 P
开头,表示句点。之后,您可以使用整数值和分配给特定句点的字符来指定每个句点。您应该查看 DateInterval
文档以了解更多详细信息。
下面的示例说明了在 PHP 中添加或减去日期和时间是多么容易。
<?php $now = new DateTime('now'); $the_interval = new DateInterval('P20Y5M20D'); $now->add($the_interval); // Output — It will be Saturday, 05 March, 2039 after 20 years, 05 months and 20 days from today. echo 'It will be '.$now->format('l, d F, Y').' after '.$the_interval->format("%Y years, %M months and %d days").' from today.'; $now = date_create('now'); $the_interval = date_interval_create_from_date_string('20 years 05 months 20 days'); date_add($now, $the_interval); // Output — It will be Saturday, 05 March, 2039 after 20 years, 05 months and 20 days from today. echo 'It will be '.$now->format('l, d F, Y').' after '.$the_interval->format("%Y years, %M months and %d days").' from today.'; ?>
您还可以使用比较运算符来比较 PHP 中的日期。这有时会派上用场。让我们使用比较运算符和其他 DateTime
方法创建一个圣诞节计数器。
<?php $now = new DateTime('today'); $christmas = new DateTime('25 December 2018'); while($now > $christmas) { $christmas->add(new DateInterval('P1Y')); } if($now < $christmas) { $interval = $now->diff($christmas); echo $interval->format('%a days').' until Christmas!'; } if($now == $christmas) { echo 'Merry Christmas :)'; } // Output — 103 days until Christmas! ?>
我们首先创建两个 DateTime
对象来存储当前时间和今年圣诞节的日期。之后,我们运行 while
循环,不断向 2018 年圣诞节日期添加 1 年,直到当前日期小于圣诞节日期。当代码在 2024 年 1 月 18 日运行时,这将很有帮助。只要圣诞节日期小于运行此脚本时的当前日期,while 循环就会增加圣诞节日期。
我们的圣诞节计数器现在可以在未来几十年内正常工作,不会出现任何问题。
有关 PHP 中 date()
的常见问题
关于从 PHP 中的 date()
函数获取不同类型的信息,时不时会出现一些常见问题。我们将尽力在这里回答所有问题。
如何获取 PHP 中的当前年份?
您可以使用 date('y')
或 date('Y')
获取 PHP 中的当前年份。使用大写字母 Y 将为您提供当前年份的所有数字,例如 2021。使用小y只会给出最后两位数字,例如21。
<?php echo date('Y'); // 2021 echo date('y'); // 21 ?>
在 PHP 中获取当前月份的正确方法是什么?
在 PHP 中,有四种不同的字符用于获取当前月份,具体取决于您想要的格式。您可以使用大写字母 F 获取月份的完整名称,例如 February,或者使用 M 获取较短的三字母格式的月份。
您还可以使用m和n以数字形式获取当前月份,这将分别为您提供带前导零和不带前导零的月份。
<?php echo date('F'); // February echo date('M'); // Feb echo date('m'); // 02 echo date('n'); // 2 ?>
如何用 PHP 获取星期几?
您还可以通过使用四个不同的字符来获取 PHP 中的星期几。大写字母 D 将用三个字母表示一周中的某一天,例如 Mon 或 Tue。使用 l(小写 L)将为您提供一周中某一天的全名。
您可以使用 w 获取一周中各天的 0(星期日)和 6(星期六)之间的数值>.
<?php echo date('D'); // Fri echo date('l'); // Friday ?>
如何在 PHP 中获取 12 小时格式的当前时间?
您可以使用 g 或 h 获取 12 小时格式的当前时间。使用g,您将获得不带任何前导零的时间,而h将添加一些前导零。可以使用a(小写字母)或A(大写字母)添加 AM 或 PM。
<?php echo date('g:i:s a'); // 5:05:19 am echo date('h:i:s A'); // 05:05:19 AM ?>
我可以在 PHP 中获取 24 小时格式的当前时间吗?
使用字符G和H将为您提供24小时格式的当前小时。 G 不会出现任何前导零,但 H 会添加前导零。
<?php echo date('G:i:s'); // 15:06:48 ?>
转义日期格式字符的最佳方法是什么?
date()
函数接受字符串作为参数,但许多字符都有明确定义的含义,例如 Y 表示年份,F 表示年份月。这意味着直接使用这些字符作为字符串的一部分可能并不总是能获得所需的结果。
如果您希望 date()
函数输出这些字符,那么您必须先对它们进行转义。这是一个例子:
<?php echo 'Today is '.date("l the jS of F Y"); // Today is Friday 2804Europe/Berlin 19th 2021f February 2021 echo 'Today is '.date("l \\t\h\\e jS \of F Y"); // Today is Friday the 19th of February 2021 ?>
某些字符(例如 t)需要两个反斜杠,因为 \t 用于制表符。如果可能,建议将您想要回显的常规字符串放在 date()
之外。否则,您将转义很多字符。
最终想法
在本教程中,我们学习了如何使用 date()
函数以所需格式输出当前日期和时间。我们还看到 date()
也可用于仅获取当前年份、月份等。之后,我们学习了如何获取当前时间戳或将有效的 DateTime
字符串转换为时间戳。最后,我们学习了如何从不同的日期中添加或减去一段时间。
我尝试在此处介绍关键的 DateTime
函数和方法。您绝对应该查看文档以了解本教程中未涵盖的功能。如果您有任何疑问,请随时在评论中告诉我。
The above is the detailed content of Date and time formatting in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In Python, we have some built-in time functions such as strftime() and datetime.now() which can be used to find the time in AM/PM format. Time in AM/PM format is used in a variety of applications such as user interfaces, reporting and documentation, data visualization, and event scheduling. When the time is between 11:59:00 midnight and 12 noon, we say AM time. Similarly, we can say that the time between 12 o'clock and 11:59:00 midnight is PM. The abbreviations AM/PM are used to indicate the exact time. Syntax uses the following syntax in the example &miinus;strftime('%I:%M:%S%p')strft

PHP date function is a powerful tool for date calculation and processing, which contains many useful functions to process date and time information. Among them, determining the day of the week for any date is a common requirement, which can be easily achieved in PHP through the date() and strtotime() functions. The following will introduce in detail how to use PHP date functions to determine the day of the week for any date, and provide specific code examples. First, you can get the day of the week of the current time through the date() function, whose format is 0 (Sunday)

In PHP language development, date formatting errors are a common problem. The correct date format is very important to programmers because it determines the readability, maintainability and correctness of the code. This article will share some tips for dealing with date formatting errors. Understanding date formats Before dealing with date formatting errors, we must first understand date formats. A date format is a string of various letters and symbols used to represent a specific date and time format. In PHP, common date formats include: Y: four-digit year (such as 20

Python regular expression is a very powerful text processing tool that can perform operations such as matching, replacing, and extracting strings. In actual development, we often need to format dates, such as converting "2022/10/01" into the format of "October 01, 2022". This article will introduce how to use Python regular expressions for date formatting. 1. Overview of Python regular expressions Python regular expression is a special string pattern, which describes a series of characters that match a certain

Java is a popular programming language that includes many powerful tools for date and time manipulation. One of the most commonly used tools is the DateFormat function, which can format date data into a specific string format. This article will introduce how to use the DateFormat function in Java for date formatting. Import the Date and DateFormat classes. Before starting to use the DateFormat function, we need to import the Date and DateFormat classes in Java.

PHP Time Processing Tips: Quickly Calculate Time Difference and Date Formatting With the rapid development of the Internet, time processing has become one of the common tasks in web development. In PHP, time processing is a relatively common requirement, such as calculating time differences, formatting dates, and other operations. This article will introduce some PHP time processing techniques, including quickly calculating time differences and date formatting, and come with some specific code examples. Calculating the time difference In many application scenarios, we need to calculate the time difference between two time points, such as calculating the time difference between two time points.

Solution Overview to Solve Java Date Formatting Exception (DateTimeParseException): In Java, date formatting is a common task. We can convert date and time to a specified format by using the SimpleDateFormat class or the new date time APIs available in Java 8 (such as DateTimeFormatter). However, sometimes when formatting dates, you may encounter DateTimePars

PHP Date Programming Guide: Discover how to use PHP to determine the day of the week for a certain date. In PHP programming, we often need to deal with date and time-related issues. One of the common needs is to determine the day of the week for a certain date. PHP provides a wealth of date and time processing functions that can easily implement this function. This article will introduce in detail how to determine the day of the week of a certain date in PHP and give specific code examples. 1. Use the date() function to get the day of the week. The date() function in PHP can be used for formatting.
