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.
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), whiley
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, buth
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 thedate()
function. It is best to consult the format character table in thedate()
function documentation for more information about special cases.
Now let's look at some practical examples of thedate()
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.
Copy after login
You can also use thedate()
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 中获取当前 Unix 时间戳的值。借助time()
函数,这非常容易。它返回一个整数值,描述自 1970 年 1 月 1 日午夜 (00:00:00) GMT 以来经过的毫秒数。
您还可以使用此功能来回返回时间。为此,您所要做的就是从time()
的当前值中减去正确的秒数,然后将结果值更改为所需的日期字符串。以下是两个示例:
您应该记住的一件重要事情是,time()
返回的时间戳值与时区无关,并且获取自 1970 年 1 月 1 日 00:00:00 UTC 以来的秒数。这意味着在特定时间点,此函数将在美国、欧洲、印度或日本返回相同的值。
获取特定日期的时间戳的另一种方法是使用mktime($hour, $min, $second, $month, $day, $year)
函数。当省略所有参数时,该函数仅使用当前本地日期和时间来计算时间戳值。此函数还可以与date()
一起使用来生成有用的日期和时间字符串。
基本上,time()
可用于来回返回一段时间,而mktime()
在您想要前往某个时间点时很有用特定时间点。
当您想要将字符串格式的不同日期和时间值转换为时间戳时,strtotime($time, [$now = time()])
函数将非常有用。该函数可以将几乎所有类型的日期时间字符串解析为时间戳。
您一定要检查有效的时间格式、日期格式、复合日期时间格式和相对日期时间格式。
使用相对日期时间格式,该函数可以轻松地将常用字符串转换为有效的时间戳值。下面的例子应该可以清楚地说明:
可以在日期中添加或减去特定的时间段。这可以借助date_add()
和date_sub()
函数来完成。您还可以使用date_diff()
函数来减去两个日期并以年、月、日或其他形式输出它们之间的差异。
通常,使用DateTime
类以面向对象的方式执行任何此类与日期和时间相关的算术比按程序执行更容易。我们将在这里尝试这两种样式,您可以选择您最喜欢的一种。
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 中添加或减去日期和时间是多么容易。
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
方法创建一个圣诞节计数器。
$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 循环就会增加圣诞节日期。
我们的圣诞节计数器现在可以在未来几十年内正常工作,不会出现任何问题。
date()
的常见问题关于从 PHP 中的date()
函数获取不同类型的信息,时不时会出现一些常见问题。我们将尽力在这里回答所有问题。
您可以使用date('y')
或date('Y')
获取 PHP 中的当前年份。使用大写字母Y将为您提供当前年份的所有数字,例如2021。使用小y只会给出最后两位数字,例如21。
在 PHP 中,有四种不同的字符用于获取当前月份,具体取决于您想要的格式。您可以使用大写字母F获取月份的完整名称,例如February,或者使用M 获取较短的三字母格式的月份。
您还可以使用m和n以数字形式获取当前月份,这将分别为您提供带前导零和不带前导零的月份。
您还可以通过使用四个不同的字符来获取 PHP 中的星期几。大写字母D将用三个字母表示一周中的某一天,例如Mon或Tue。使用l(小写 L)将为您提供一周中某一天的全名。
您可以使用w获取一周中各天的0(星期日)和6(星期六)之间的数值>.
您可以使用g或h获取 12 小时格式的当前时间。使用g,您将获得不带任何前导零的时间,而h将添加一些前导零。可以使用a(小写字母)或A(大写字母)添加 AM 或 PM。
使用字符G和H将为您提供24小时格式的当前小时。G不会出现任何前导零,但H会添加前导零。
date()
函数接受字符串作为参数,但许多字符都有明确定义的含义,例如Y表示年份,F表示年份月。这意味着直接使用这些字符作为字符串的一部分可能并不总是能获得所需的结果。
如果您希望date()
函数输出这些字符,那么您必须先对它们进行转义。这是一个例子:
某些字符(例如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!