gpt4 book ai didi

php - 什么是 Unix 时间戳以及为什么要使用它?

转载 作者:IT王子 更新时间:2023-10-28 23:49:21 31 4
gpt4 key购买 nike

什么是 Unix 时间戳?在 PHP 中,当处理日期时,函数 strtotime() 输出一些整数值——那是什么?我试图了解这个但我得不到满意的答案,特别是为什么我们需要使用 strtotime() 转换日期。

最佳答案

什么是 Unix 时间戳

简单地说,Unix 时间戳是一种将时间跟踪为运行总秒数的方法。这个计数从 1970 年 1 月 1 日 UTC 的 Unix 纪元开始。因此,Unix 时间戳只是特定日期和 Unix 纪元之间的秒数。还应该指出的是,无论您在地球上的哪个位置,这个时间点在技术上都不会改变。这对于在线和客户端的动态和分布式应用程序中跟踪和分类过时信息的计算机系统非常有用。许多网站管理员使用 Unix 时间戳的原因是它们可以一次代表所有时区。欲了解更多信息,请阅读 Wikipedia article .

什么是strtotime(),它有什么用处

顾名思义,strtotime()函数用于将日期字符串转换为Unix时间戳(str to time)。

来自 [strtotime() 的 PHP 手册文档] 2 :

strtotime — Parse about any English textual datetime description into a Unix timestamp

例如,假设您想要获取日期 2013 年 12 月 25 日 的 Unix 时间戳,那么您可以像这样使用 strtotime():

echo strtotime("25 December 2013"), "\n";       // => 1387909800

strtotime() 还可以处理相对时间和日期格式。例如,考虑以下情况:

echo strtotime("+1 month"), "\n";               // => 1390980039
echo strtotime("last day of next month"), "\n"; // => 1391152839

这些是一些基本示例。 strtotime() 也可以处理非常复杂的日期格式。见 the documentation了解更多信息。

什么时候应该使用时间戳

无论地区如何,Unix 时间戳的解释都是相同的,并且无论时区如何,都是从同一时间点计算的。如果您有一个在多个时区使用的 Web 应用程序,并且您需要日期/时间来反射(reflect)各个用户的设置,请使用时间戳。

对于strtotime(),多用于日期格式之间的转换。由于 strtotime() 几乎可以解析任何日期字符串,因此它用于将日期字符串转换为时间戳。获得时间戳后,您可以使用 date() 随意格式化它。 ,或类似的功能。

strtotime()

的限制

在 32 位系统上,整数的最大值为 2,147,483,647。可以用这种方式表示的最远时间是 2038 年 1 月 19 日星期二 03:14:07 UTC。这也称为 Year 2038 problem .

PHP manual 中查看此注释:

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.

使用 DateTime 对象

如果您使用的日期在 1901 年 12 月 13 日2038 年 1 月 19 日 范围之外,请考虑使用 PHP 的 DateTime可以在更广泛的日期范围内工作的对象。 DateTime 在任一方向上都可以代表大约 2930 亿年。

DateTime 类在 PHP 版本 >= 5.2.0 上可用。如果您运行的 PHP 版本高于 >= 5.2.0,那么在处理日期和时间时应该使用 DateTime。这是最好的方法。如果您使用的是旧 PHP 版本,请已经升级。 5.3.0 之前的任何东西都是古老的。

这里有一些关于 DateTime 的好文章:

还有一本书:

关于php - 什么是 Unix 时间戳以及为什么要使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20822821/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com