php时间怎么转换成时间戳
-
PHP中可以使用strtotime()函数将时间转换成时间戳。
strtotime()函数的语法如下:
“`
int strtotime ( string $time [, int $now = time() ] )
“`
其中,$time是需要转换的时间字符串,$now是可选参数,表示参照时间,默认为当前时间。示例代码如下:
“`
$time = “2021-01-01 12:00:00”;
$timestamp = strtotime($time);
echo $timestamp;
“`运行结果:
“`
1609488000
“`在上面的示例中,将字符串”2021-01-01 12:00:00″转换成了时间戳1609488000。
需要注意的是,strtotime()函数对时间字符串的要求比较宽松,可以接受多种格式的时间字符串,例如”2021-01-01″、”2021/01/01″、”January 1, 2021″等,甚至可以识别相对时间表达式,例如”+1 day”、”next friday”等。
如果转换失败,strtotime()函数会返回false。
另外,如果需要将时间戳转换成可读的时间字符串,可以使用date()函数,如下所示:
“`
$timestamp = 1609488000;
$time = date(“Y-m-d H:i:s”, $timestamp);
echo $time;
“`运行结果:
“`
2021-01-01 12:00:00
“`以上就是将时间转换成时间戳的方法。
2年前 -
在PHP中,可以使用函数 strtotime() 将时间字符串转换为时间戳。
strtotime() 函数接受一个时间字符串作为参数,并尝试将其转换为UNIX时间戳。它可以识别多种不同的时间格式,并返回对应的时间戳。
下面是使用strtotime()函数将时间字符串转换为时间戳的示例代码:
“`php
$timeString = “2021-05-01 12:30:00”;
$timestamp = strtotime($timeString);
echo $timestamp;
“`上述代码将输出 “1619868600”,即时间字符串 “2021-05-01 12:30:00” 对应的时间戳。
strtotime() 函数还支持一些特殊的相对时间格式,例如:
– “+1 day”,表示相对于当前时间的明天
– “-1 week”,表示相对于当前时间的一周前
– “next Monday”,表示下个周一的时间
– “last day of this month”,表示这个月最后一天的时间下面是一个使用strtotime()函数处理相对时间的示例代码:
“`php
$nextDay = strtotime(“+1 day”);
$lastWeek = strtotime(“-1 week”);
$nextMonday = strtotime(“next Monday”);
$lastDayOfMonth = strtotime(“last day of this month”);echo “明天的时间戳:” . $nextDay . “
“;
echo “一周前的时间戳:” . $lastWeek . “
“;
echo “下个周一的时间戳:” . $nextMonday . “
“;
echo “这个月最后一天的时间戳:” . $lastDayOfMonth . “
“;
“`上述代码将输出当前时间的明天、一周前、下个周一和这个月最后一天的时间戳。
使用strtotime()函数,可以方便地将时间字符串转换为时间戳,并且支持处理相对时间。
2年前 -
在PHP中,可以使用`strtotime()`函数将时间转换为时间戳。它接受一个时间字符串作为参数,并返回一个时间戳,表示该时间字符串所代表的时间。下面是使用`strtotime()`函数将时间转换为时间戳的方法:
“`php
$date_string = “2022-01-01 12:00:00”; // 需要转换的时间字符串
$timestamp = strtotime($date_string); // 使用strtotime()函数将时间字符串转换为时间戳
echo $timestamp; // 输出时间戳
“`上述代码中,我们定义了一个时间字符串`$date_string`,它表示2022年1月1日12点。然后,我们使用`strtotime()`函数将该时间字符串转换为时间戳,并将结果存储在变量`$timestamp`中。最后,使用`echo`语句输出时间戳。
你也可以使用`date()`函数将时间戳转换为可读的日期字符串。下面是一个示例:
“`php
$timestamp = 1640995200; // 时间戳
$date_string = date(“Y-m-d H:i:s”, $timestamp); // 使用date()函数将时间戳转换为日期字符串
echo $date_string; // 输出日期字符串
“`上述代码中,我们定义了一个时间戳`$timestamp`,它表示2022年1月1日12点的时间戳。然后,我们使用`date()`函数将该时间戳转换为可读的日期字符串,并将结果存储在变量`$date_string`中。最后,使用`echo`语句输出日期字符串。
使用`strtotime()`和`date()`函数结合起来,你可以实现将时间转换为时间戳,以及将时间戳转换为可读的日期字符串的功能。
2年前