验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

怎么在PHP中实现字符串转时间戳的功能

阅读:362 来源:乙速云 作者:代码code

怎么在PHP中实现字符串转时间戳的功能

一、PHP 中时间戳的概念

在 PHP 中,时间戳(timestamp)是表示某一时间点的整数,精确到秒级别。从 Unix 时间开始算起,每经过一秒钟,时间戳就会增加一个值。Unix 时间是指从 1970 年 1 月 1 日 00:00:00(格林威治标准时间)起至现在的总秒数。

PHP 中提供了 time() 函数可以获取当前时间的时间戳,例如:

$timeStamp = time();
echo $timeStamp; // 输出当前时间的时间戳

二、PHP 中的字符串转时间戳函数

在 PHP 中,我们可以使用 strtotime() 函数来将字符串转成时间戳。该函数的原型如下:

int strtotime(string $time [, int $now = time() ]);

其中,$time 是需要转换的时间字符串,$now 是可选参数,表示当前时间的时间戳,默认时间戳是当前时间的时间戳。

如果 $time 是一个合法的日期字符串,那么 strtotime() 函数将返回该日期的时间戳,例如:

$timestamp = strtotime('2021-09-28');
echo $timestamp; // 输出 1632777600

如果 $time 无法转换成时间戳,strtotime() 函数将返回 false,例如:

$timestamp = strtotime('not a valid date');
var_dump($timestamp); // 输出 bool(false)

除了日期字符串,strtotime() 函数还可以处理相对时间字符串,例如:

$timestamp = strtotime('now');
echo $timestamp; // 输出当前时间的时间戳

$timestamp = strtotime('+1 day');
echo $timestamp; // 输出明天这个时间的时间戳

三、PHP 中的时间戳转字符串函数

在 PHP 中,我们同样可以使用 date() 函数将时间戳格式化成指定的日期字符串。该函数的原型如下:

string date(string $format [, int $timestamp = time() ]);

其中,$format 是日期格式字符串,用于指定日期字符串的格式,$timestamp 是可选参数,表示需要格式化的时间戳,默认是当前时间的时间戳。

例如,将时间戳格式化成年月日的字符串可以这样实现:

$dateString = date('Y-m-d', 1632777600);
echo $dateString; // 输出 2021-09-28

四、PHP 中日期字符串和时间戳的相互转化

我们可以结合 strtotime() 函数和 date() 函数,实现日期字符串和时间戳的相互转换。例如,将日期字符串转换成时间戳可以这样实现:

$dateString = '2021-09-28';
$timestamp = strtotime($dateString);
echo $timestamp; // 输出 1632777600

将时间戳转换成日期字符串可以这样实现:

$timestamp = 1632777600;
$dateString = date('Y-m-d', $timestamp);
echo $dateString; // 输出 2021-09-28

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>