PHP中如何将string类型转为日期格式?
在PHP中,我们可以使用strtotime或DateTime两种方法将string类型的数据转换为日期格式。下面我们分别介绍一下这两种方法的使用。
方法一:使用strtotime()
strtotime()函数可以将任何字符串型的日期或时间转换成 Unix 时间戳,它的语法如下:
strtotime(string $datetime [, int $now ] ) : int|false
其中,参数$datetime表示需要转化的日期或时间字符串;$now参数是可选参数,是基于指定时间戳的数字,用来规定$str字符串的指定偏移量。返回值成功返回时间戳,失败返回false。
举个例子:
我们可以使用strtotime()函数将"2020-09-10"转换为时间戳:
$time=strtotime("2020-09-10");
echo $time;
输出结果为:
1599676800
注意,如果字符串格式不符合strtotime()函数的要求(不符合日期格式),那么转换结果可能会是不准确的,比如:
$time=strtotime("2020-13-10");
echo $time;
输出结果为:
false
因此,在使用strtotime()函数进行字符串日期转换时一定要注意日期格式的正确性。
方法二:使用DateTime类
PHP中的DateTime类可以通过实例化一个DateTime对象的形式来进行字符串日期的转换,它的语法如下:
DateTime::__construct(string $time = "now", DateTimeZone|null $timezone = null)
其中,参数$time表示需要转化的日期或时间字符串,支持的格式和strtotime()函数一致;$timezone参数是可选的,用于指定时区。
举个例子:
我们可以使用DateTime类将"2020-09-10"转换为时间戳:
$time=new DateTime("2020-09-10");
echo $time->getTimestamp();
输出结果为:
1599676800
同样的,如果我们输入的日期格式不正确,也会导致无法正确转换:
$time=new DateTime("2020-13-10");
echo $time->getTimestamp();
输出结果为:
PHP Notice: DateTime::__construct(): Failed to parse time string (2020-13-10) at position 6 (3): Unexpected character in /...
需要注意的是,DateTime对象不能直接打印,需要使用getTimestamp()方法获取时间戳值。除此之外,DateTime类还有很多其他的方法可以对日期进行操作和计算。
总结
在PHP中将字符串日期转换为日期格式一般使用strtotime()函数或DateTime类。如果字符串格式正确,两种方法都可以实现日期转换,并且都可以进行时间的加减操作。dateTime简化了时间转化的复杂度,可读性更高,strtotime更加灵活,后期的操作更加容易。
有了这两种方法,我们就能够轻松地将字符串日期转换成格式化的日期,从而更好地与各种时间函数进行交互。