php怎么把字符串变成时间
-
将字符串转换为时间,可以使用PHP中的date()函数和strtotime()函数实现。
1. 使用date()函数:
date()函数可以将时间戳格式化为指定的日期格式。可以将字符串先转换为时间戳,然后再用date()函数进行格式化。示例代码:
“`
“`解释:
首先,将字符串”2021-09-28 10:30:00″转换为时间戳,使用strtotime()函数。然后将时间戳格式化为”Y-m-d H:i:s”的日期格式,使用date()函数。最后输出结果为”2021-09-28 10:30:00″。2. 使用strtotime()函数:
strtotime()函数可以将人类可读的日期时间字符串转换为Unix时间戳。示例代码:
“`
“`解释:
将字符串”2021-09-28 10:30:00″转换为时间戳,使用strtotime()函数。最后输出结果为时间戳,例如1632798600。无论是使用date()函数还是strtotime()函数,都需要注意传入的日期时间字符串的格式与函数的要求相匹配。常用的日期时间格式包括 “Y-m-d H:i:s”、”YmdHis” 等。
以上就是使用PHP将字符串转换为时间的方法。希望对你有帮助!
2年前 -
将字符串转换为时间的方法有多种,具体取决于字符串的格式。下面列出了一些常见的方法:
1. 使用strtotime()函数:
“`php
$string = “2021-10-01 10:30:00”;
$time = strtotime($string);
“`
该函数将返回一个UNIX时间戳,表示自1970年1月1日以来的秒数。2. 使用date_create() 和 date_format()函数:
“`php
$string = “2021-10-01 10:30:00”;
$time = date_create($string);
$formattedTime = date_format($time, ‘Y-m-d H:i:s’);
“`
date_create()函数将返回一个DateTime对象,可以通过date_format()函数将其转换为指定格式的字符串。3. 使用DateTime类的静态方法:
“`php
$string = “2021-10-01 10:30:00”;
$time = DateTime::createFromFormat(‘Y-m-d H:i:s’, $string);
$formattedTime = $time->format(‘Y-m-d H:i:s’);
“`
DateTime::createFromFormat()方法允许你指定输入字符串的格式,然后返回一个DateTime对象。format()方法可以将DateTime对象转换为指定格式的字符串。4. 使用strtotime()和date()函数的组合:
“`php
$string = “2021-10-01 10:30:00”;
$time = strtotime($string);
$formattedTime = date(‘Y-m-d H:i:s’, $time);
“`
这种方法将先使用strtotime()函数将字符串转换为UNIX时间戳,然后使用date()函数将时间戳转换为指定格式的字符串。5. 使用DateTimeImmutable类:
“`php
$string = “2021-10-01 10:30:00”;
$time = DateTimeImmutable::createFromFormat(‘Y-m-d H:i:s’, $string);
$formattedTime = $time->format(‘Y-m-d H:i:s’);
“`
DateTimeImmutable类是DateTime类的不可变版本,可以通过createFromFormat()方法将字符串转换为DateTimeImmutable对象,然后使用format()方法将其转换为指定格式的字符串。无论使用哪种方法,都要确保字符串的格式与指定的格式相匹配,以确保正确的转换。
2年前 -
在PHP中,可以使用`strtotime()`函数将字符串转换为日期和时间。`strtotime()`函数将字符串解析为UNIX时间戳(自1970年1月1日以来所经过的秒数),然后可以通过`date()`函数将UNIX时间戳转换为指定格式的日期和时间。
下面是使用`strtotime()`和`date()`函数将字符串转换为时间的步骤和示例代码:
步骤1:定义一个包含日期和时间的字符串。
“`php
$dateString = “2022-05-20 14:30:00”;
“`步骤2:使用`strtotime()`函数将字符串转换为UNIX时间戳。
“`php
$timestamp = strtotime($dateString);
“`步骤3:使用`date()`函数将UNIX时间戳转换为指定格式的日期和时间。
“`php
$formattedDate = date(“Y-m-d H:i:s”, $timestamp);
“`完整的代码如下所示:
“`php
$dateString = “2022-05-20 14:30:00”;
$timestamp = strtotime($dateString);
$formattedDate = date(“Y-m-d H:i:s”, $timestamp);echo $formattedDate; // 输出:2022-05-20 14:30:00
“`通过上述代码,我们可以将字符串`”2022-05-20 14:30:00″`转换为时间格式,并将其格式化为`”Y-m-d H:i:s”`的形式。
另外,`strtotime()`函数还支持其他日期和时间格式,例如:
– `strtotime(“now”)`:当前日期和时间
– `strtotime(“tomorrow”)`:明天的日期和时间
– `strtotime(“+1 day”)`:当前日期加上1天
– `strtotime(“next Monday”)`:下个周一的日期和时间使用`strtotime()`函数可以方便地将字符串转换为日期和时间,同时还可以与其他日期和时间函数结合使用,进行更复杂的日期和时间处理。
2年前