php怎么把时间转为时间戳
-
PHP中可以使用strtotime函数将时间转换为时间戳。
strtotime函数接收一个字符串参数,返回与参数给定的日期/时间相关的UNIX时间戳。
以下是示例代码:
“`
$datetime = ‘2022-01-01 12:00:00’;
$timestamp = strtotime($datetime);
echo $timestamp;
“`在上述代码中,变量$datetime存储了一个字符串形式的日期时间,使用strtotime函数将$datetime转换为时间戳,并将结果保存在$timestamp变量中。最后,使用echo语句打印出时间戳的值。
需要注意的是,strtotime函数对于不同的日期时间格式有不同的处理方式,例如:
“`
$datetime = ‘2022-01-01 12:00:00’; // 年-月-日 时:分:秒
$timestamp = strtotime($datetime);$datetime = ‘2022/01/01 12:00:00’; // 年/月/日 时:分:秒
$timestamp = strtotime($datetime);$datetime = ‘Jan 1, 2022 12:00:00 PM’; // 月 日, 年 时:分:秒 AM/PM
$timestamp = strtotime($datetime);
“`通过调整输入参数的格式,可以将不同格式的日期时间转换为时间戳。
总结一下,使用strtotime函数可以将字符串形式的日期时间转换为对应的时间戳。
2年前 -
在PHP中,可以使用time()函数将当前时间转换为时间戳,或者使用strtotime()函数将一个指定日期时间字符串转换为时间戳。
1. 使用time()函数将当前时间转为时间戳:
“`php
$timestamp = time();
echo $timestamp;
“`2. 使用strtotime()函数将一个指定日期时间字符串转为时间戳:
“`php
$dateStr = ‘2022-01-01 12:00:00’;
$timestamp = strtotime($dateStr);
echo $timestamp;
“`3. strtotime()函数也可以处理相对时间表达式,例如”tomorrow”、”next week”等,它会将这些相对时间转换为时间戳:
“`php
$timestamp = strtotime(‘tomorrow’);
echo $timestamp;
“`4. 如果指定的日期时间字符串无法解析或者格式不正确,strtotime()函数会返回false。因此,在使用之前最好先检查返回值是否为false。
5. 使用date()函数可以将时间戳格式化为想要的日期时间字符串,例如:
“`php
$timestamp = time();
$dateStr = date(‘Y-m-d H:i:s’, $timestamp);
echo $dateStr;
“`以上是将时间转为时间戳的几种常用方法,可以根据具体需求选择适合的方法。注意,PHP内部时间戳通常是基于Unix时间戳,表示自1970年1月1日0时0分0秒以来的秒数。
2年前 -
在PHP中,你可以使用strtotime函数将时间字符串转换为时间戳。
strtotime函数接受一个日期/时间字符串作为参数,并尝试将其转换为UNIX时间戳。以下是使用strtotime函数的一些示例:
“`php
$dateString = “2022-01-01 00:00:00”;
$timestamp = strtotime($dateString);
echo $timestamp; // 输出:1640966400
“`在上述示例中,我们将”2022-01-01 00:00:00″字符串传递给strtotime函数,并将返回的时间戳存储在变量$timestamp中。然后,我们使用echo语句将时间戳输出到屏幕上。
strtotime函数还支持更多的日期/时间格式。例如,你可以使用以下日期格式:
– “now”:当前日期和时间
– “tomorrow”:明天的日期
– “+1 day”:从当前日期开始的下一天
– “-1 day”:从当前日期开始的前一天
– “next Monday”:下周一的日期
– “last Sunday”:上周日的日期以下是使用相对日期/时间格式的示例:
“`php
$today = strtotime(“today”);
echo $today; // 输出:当前日期的时间戳$tomorrow = strtotime(“tomorrow”);
echo $tomorrow; // 输出:明天的日期的时间戳$nextWeek = strtotime(“next week”);
echo $nextWeek; // 输出:下周的日期的时间戳
“`此外,你还可以使用特定格式的日期/时间字符串。例如,以下是使用”Y-m-d H:i:s”格式的示例:
“`php
$dateString = “2022-01-01 00:00:00”;
$timestamp = strtotime($dateString);
$formattedDate = date(“Y-m-d H:i:s”, $timestamp);
echo $formattedDate; // 输出:2022-01-01 00:00:00
“`在上述示例中,我们使用date函数将时间戳格式化为指定的日期/时间字符串。
总结:要将时间转换为时间戳,只需使用strtotime函数。你可以使用特定的日期/时间字符串或相对日期/时间格式作为函数的参数。然后,可以使用date函数将时间戳格式化为指定的日期/时间字符串。
2年前