我在尝试将字符串转换为时间时遇到了一些麻烦。
我的代码是:
$time = strtotime("14 November, 2013 2:30 AM");
echo $time ."<br />";
echo date("m/d/Y", $time);
我知道strtotime并不神奇,我检查了可接受的日期/时间格式,但我不确定如何在不先将其转换为时间的情况下将字符串转换为另一个字符串。
实现这一目标的最简单方法是什么?
查看 DateTime::createFromFormat 然后在创建的 DateTime 实例上调用 format 。
就像是:
$yourTimeString = '14 November, 2013 2:30 AM';
$date = DateTime::createFromFormat('d F, Y h:i A', $yourTimeString);
echo $date->format('m/d/Y');
<?php
// here we assume "day month, year time AMPM"
$date = "14 November, 2013 2:30 AM";
// assign a variable to each part of the string
list($day,$month,$year,$time,$ampm) = explode(" ",$date);
// remove the commas at the end of the month
$month = str_replace(',','',$month);
// Now we rewrite the strtotime string
$time = strtotime($month . " " . $day . ", " . $year . " " . $time . " " . $ampm);
echo $time ."<br />";
echo date("m/d/Y", $time);
phpdate()
函数允许使用自然语言字符串来解析日期,
for Ex:
echo date("d-M-Y", strtotime("first monday of 2019-07")); // returns first monday of july 2019
echo date("d-M-Y", strtotime("last sat of July 2008"));
您可以在此处找到将日期解析为自然语言的 php 说明。