如何提取 y-m-d 格式的日期值?

How to extract the values of a date in y-m-d format?

假设我有这个日期:2016-07-27。我想要实现的是:

$year = 2016;
$month = 07;
$day = 27;

我尝试过的:

如何提取破折号之间的数字并将它们存储到下面的变量中,如上所示?

不要重新发明轮子 - date_parse 会为您完成所有繁重的工作:

$parsed = date_parse('2016-07-27');
$year = $parsed['year'];
$month = $parsed['month'];
$day = $parsed['day'];

如果它是一个不会改变其格式的字符串,那么您可以简单地这样做:

$date = '2016-07-27';
list($year, $month, $day) = explode('-', $date);

echo $year; // 2016
echo $month; // 07
echo $day; // 27

但是,如果日期格式发生变化,那么您应该使用 date_parse 或其他 DateTime 方法。