如果我有一个格式为mm-dd-YYYY的PHP字符串(例如,10-16-2003),我如何正确地将其转换为日期,然后是YYYY-mm-dd格式的日期时间?我同时要求Date和DateTime的唯一原因是,我需要一个在一个地方,另一个在不同的地方。
当前回答
既然没人提到这一点,这里有另一种方法:
$date = date_create_from_format("m-d-Y", "10-16-2003")->format("Y-m-d");
其他回答
我尝试了上面所有的答案,但失败了,在我的情况下,我构建了一个函数,获得以下格式“YYYY/mm/dd”的日期字符串。所以我认为像这样爆炸弦会更好:
$old_date = explode('/', $coming_date_str);
new_data =美元old_date old_date美元[0]。”——“。[1],”——“。美元old_date [2];//将字符串转换为上述所有帖子并完成
$new_date = date('Y-m-d', strtotime($new_data));
$new_date = DateTime::createFromFormat("Y-m-d", new_date);
在第一次约会时使用strtotime(),然后date('Y-m-d')将其转换回来:
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2003-10-16
请注意,在strtotime()函数中使用正斜杠/和连字符-是有区别的。引用自php.net:
m/d/y或d-m-y格式的日期 可以通过查看 在不同的 组件:如果分隔符为a /,则美式的m/d/y为 假设;而如果分隔符是a 破折号(-)或点(.),然后是 采用欧洲d-m-y格式。 为了避免潜在的歧义,最好尽可能使用ISO 8601 (YYYY-MM-DD)日期或DateTime::createFromFormat()。
对我来说,这样做很有效:
$stringDate = "2022-02-24T17:15:00"; (如果你只发送日期“2022-02-24”,它会将时间填充为00:00:00)。
$dateFormat = 新的日期时间($miStringDate);
如果你希望接受日期使用美式排序(月,日,年)的欧式格式(使用破折号或句号作为日,月,年),同时仍然接受其他格式,你可以扩展DateTime类:
/**
* Quietly convert European format to American format
*
* Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
* as well as all other built-in formats
*
*/
class CustomDateTime extends DateTime
{
public function __construct(string $time="now", DateTimeZone $timezone = null)
{
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
$time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );
parent::__construct($time, $timezone);
}
}
// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');
// => '2019-07-24'
或者,你可以让一个函数接受m-d-Y并输出Y-m-d:
/**
* Accept dates in various m, d, y formats and return as Y-m-d
*
* Changes PHP's default behaviour for dates with dashes or dots.
* Accepts:
* m-d-y, m-d-Y, Y-m-d,
* m.d.y, m.d.Y, Y.m.d,
* m/d/y, m/d/Y, Y/m/d,
* ... and all other formats natively supported
*
* Unsupported formats or invalid dates will generate an Exception
*
* @see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
* @param string $d various representations of date
* @return string Y-m-d or '----' for null or blank
*/
function asYmd($d) {
if(is_null($d) || $d=='') { return '----'; }
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
$d = str_replace(['-','.'], '/', $d);
return (new DateTime($d))->format('Y-m-d');
}
// usage:
<?= asYmd('7-24-2019') ?>
// or
<?php echo asYmd('7-24-2019'); ?>
既然没人提到这一点,这里有另一种方法:
$date = date_create_from_format("m-d-Y", "10-16-2003")->format("Y-m-d");
推荐文章
- 解析日期没有时区javascript
- 如何创建今天午夜和明天午夜的Java日期对象?
- 将字符串数组转换为字符串
- 使用PHP加密和解密密码的最佳方法是什么?
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PowerShell格式化日期时间
- 我可以将c#字符串值转换为转义字符串文字吗?