2017-02-16 57 views

回答

1

让我们假设你有一个名为$date

变量字符串
$date = '2017-01-20'; 

可以explode它变成一个list如果您确定的格式是一致的:

list($year, $month, $day) = explode("-", $date, 3); 

您可以将日期转换为使用strtotime在其他功能使用像date时间整数。这具有能够测试,这是一个结构良好的日期额外的好处:

$time = strtotime($date); 
if ($time === false) die("Bad date format: $date."); 
$year = date('Y', $time); 
$month = date('m', $time); // 'n' if you don't want leading zero 
$day = date('d', $time); // 'j' if you don't want leading zero 

由于jasonmoqio指出,既然你问了速度最快,substr是一点点比爆炸更快。 (在我的工作站上,循环substr与爆炸1000万次相比爆炸只产生了千分之一秒的改善,所以除非这个循环运行数百万次,否则你不会注意到它的差异,应该选择。代码的可读性)

$year = substr($date, 0, 4); 
$month = substr($date, 5, 2); 
$day = substr($date, 8, 2); 
+0

你的工作,但它比'substr'慢慢 – jasonmoqio

1

好吧,如果你知道输出将始终是其格式为“YYYY-MM-DD”的字符串,最基本的做法是:

<?php 

    $query = ... //query is your string "YYYY-MM-DD" 
    $year = substr($query, 0, 4); 
    $month = substr($query, 5, 2); 
    $day = substr($query, 8, 2); 

    echo $month; 
    echo $day; 
    echo $year; 
?> 
+0

substr的第三个参数是长度,而不是位置。所以第一个应该是'$ year = substr($ date,0,4);'等等。 – redreinard

+0

我很抱歉这门语言搞砸了。我的回答已被编辑。谢谢! –

+0

抱歉再次发生错误,但月份和日期需要长度为2,长度不是基于0的。 – redreinard

0

试试这个:

$date = new DateTime('2017-01-20'); 
echo 'Year:'.$date->format("Y"); 
echo 'Month:'.$date->format("m"); 
echo 'Day:'.$date->format("d"); 

输出:

Year: 2017 
Month: 01 
Day: 20 
0

如果你想快速从MySQL获得的日期,请尝试使用正则表达式是这样的。

if (preg_match('/^(?P<year>\d+)[-\/](?P<month>\d+)[-\/](?P<day>\d+)$/', $your_date, $matches)) { 
    $mydate = $matches['year'] . "-" . $matches['month'] . "-" . $matches['day']; 
    $whatever = date('Y-m-d', strtotime($tgl)); 
    // You can echo it... 
    // echo $matches['year']; 
    // echo $matches['month']; 
    // echo $matches['day']; 
} 

希望这能帮到你。 :D

相关问题