我试图将日期从yyyy-mm-dd转换为dd-mm-yyyy(但不是SQL);然而,我不知道日期函数如何需要时间戳,我无法从这个字符串中获得时间戳。
这怎么可能呢?
我试图将日期从yyyy-mm-dd转换为dd-mm-yyyy(但不是SQL);然而,我不知道日期函数如何需要时间戳,我无法从这个字符串中获得时间戳。
这怎么可能呢?
当前回答
您可以尝试strftime()函数。简单示例:strftime($time, '%d %m %Y');
其他回答
有两种实现方法:
1.
$date = strtotime(date);
$new_date = date('d-m-Y', $date);
2.
$cls_date = new DateTime($date);
echo $cls_date->format('d-m-Y');
如果你想避免strtotime转换(例如,strtotime不能解析你的输入),你可以使用,
$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('d-m-Y');
或者,相当于:
$newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y');
你首先给它$dateString的格式。然后你告诉它你想要的$newDateString的格式。
或者如果source-format总是“Y-m-d”(yyyy-mm-dd),那么只需使用DateTime:
<?php
$source = '2012-07-31';
$date = new DateTime($source);
echo $date->format('d.m.Y'); // 31.07.2012
echo $date->format('d-m-Y'); // 31-07-2012
?>
$newDate = preg_replace("/(\d+)\D+(\d+)\D+(\d+)/","$3-$2-$1",$originalDate);
此代码适用于所有日期格式。
由于您的旧日期格式,您可以更改替换变量的顺序,例如$3-$1-$2。
还有一种模糊的可能性:
$oldDate = '2010-03-20'
$arr = explode('-', $oldDate);
$newDate = $arr[2].'-'.$arr[1].'-'.$arr[0];
我不知道我是否会使用它,但仍然:)
使用strtotime()和date():
$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));
(请参阅PHP站点上的strtotime和date文档。)
请注意,这是原始问题的快速解决方案。对于更广泛的转换,你应该使用DateTime类来解析和格式化:-)