简单问题:如何将日期 (08-17-2011) 拆分为月、日、年?PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7103617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:00:56  来源:igfitidea点击:

Simple Question: How to split date (08-17-2011) into month, day, year? PHP

phpvariablesdatetimesplit

提问by David Meyer

I have a variable called $orderdate and it is set to a date format like this mm-dd-yyyy.

我有一个名为 $orderdate 的变量,它被设置为类似 mm-dd-yyyy 的日期格式。

In PHP how would I split this variable into $month, $day, $year?

在 PHP 中,我如何将此变量拆分为 $month、$day、$year?

Thanks for your help.

谢谢你的帮助。

回答by binaryLV

If you're sure about the format of input value, then:

如果您确定input value的格式,则:

$orderdate = explode('-', $orderdate);
$month = $orderdate[0];
$day   = $orderdate[1];
$year  = $orderdate[2];

You could also use preg_match():

您还可以使用preg_match()

if (preg_match('#^(\d{2})-(\d{2})-(\d{4})$#', $orderdate, $matches)) {
    $month = $matches[1];
    $day   = $matches[2];
    $year  = $matches[3];
} else {
    echo 'invalid format';
}

Additionally, you can use checkdate()to validate the date.

此外,您可以使用checkdate()来验证日期。

回答by Kokos

If you are not certainabout the input format you can also do the following:

如果您不确定输入格式,您还可以执行以下操作:

$time  = strtotime($input);
$day   = date('d',$time);
$month = date('m',$time);
$year  = date('Y',$time);

回答by Bhanu Krishnan

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

回答by omar j

A good approach is to use date_parse_from_format().

一个好方法是使用date_parse_from_format()

For your example:

对于您的示例:

$dateStr = '03-27-2015';
$dateArray = date_parse_from_format('m-d-Y', $dateStr);

This gives $dateArrayas:

这给出$dateArray

Array
(
    [year] => 2015
    [month] => 3
    [day] => 27
    [hour] => 
    [minute] => 
    [second] => 
...
)

回答by RiaD

Use explodeto split string

使用explode来分割字符串

list($m,$d,$y)=explode('-',$date);