php如何将date转换string?

20次阅读
没有评论

PHP中可以使用date()函数将日期时间转换为字符串。该函数的语法如下:

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

其中,第一个参数$format表示要输出的日期时间格式。第二个参数$timestamp表示时间戳,可选,默认为当前时间。

示例代码如下:

<?php
// 将当前时间转换为字符串,默认格式为年-月-日 时:分:秒
$date1 = date('Y-m-d H:i:s');
echo $date1 . "\n"; // 输出:2021-10-10 10:10:10

// 将指定时间(时间戳为1633803610,即2021-10-10 10:10:10)转换为字符串,指定格式为年/月/日 时:分
$date2 = date('Y/m/d H:i', 1633803610);
echo $date2; // 输出:2021/10/10 10:10
?>

上述代码使用date函数将日期时间转换为字符串,并指定输出的格式,分别输出了默认格式和指定格式的日期时间字符串。

注意,在输出日期时间时,需要使用echo或print等输出函数。

正文完
 
评论(没有评论)