简体   繁体   English

在PHP中将格式化日期分解为单个月/日/年小时/分钟/秒

[英]break apart formatted date into individual month/day/year hour/minute/second in php

I have a date in the following format 我有以下格式的日期

November 18, 2009, 3:00PM

How can i break that up so that i can store each value as its own variable? 我怎样才能打破这一点,以便我可以将每个值存储为自己的变量?

such as... 如...

$month //November
$day //18
$year //2009
$hour //03
$minute //00
$ampm //PM

Use the 'date_parse' ( http://nl2.php.net/manual/en/function.date-parse.php ) function. 使用'date_parse'( http://nl2.php.net/manual/en/function.date-parse.php )函数。 It returns an array with the parsed items: 它返回一个包含已解析项的数组:

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] => 
)

Convert your date into a timestamp, then with the timestamp you can easily get your parts. 将您的日期转换为时间戳,然后使用时间戳您可以轻松获取您的零件。 An other way is using a regular expression. 另一种方法是使用正则表达式。

$str = "November 18, 2009, 3:00PM";
list($month,$day,$year,$time) = preg_split('/[ ,]/',$str,false,PREG_SPLIT_NO_EMPTY);
preg_match('/([0-9]+):([0-9]+)([AP]M)/',$time,$timeparts);
list($time,$hour,$minute,$ampm) = $timeparts;

echo "\$month  $month\n";
echo "\$day    $day\n";
echo "\$year   $year\n";
echo "\$hour   $hour\n";
echo "\$minute $minute\n";
echo "\$ampm   $ampm\n";

Output 产量

$month  November
$day    18
$year   2009
$hour   3
$minute 00
$ampm   PM

More complex solution. 更复杂的解决方案 If your dates may be in the different standards you can use date() function ( http://php.net/manual/en/function.date.php ) + strtotime() function ( http://php.net/manual/en/function.strtotime.php ), which parse string and returns the unix timestamp. 如果您的日期可能是不同的标准,您可以使用date()函数( http://php.net/manual/en/function.date.php)+ strtotime()函数( http://php.net/manual /en/function.strtotime.php ),解析字符串并返回unix时间戳。

For example, if you want to get a year from your date string you could write next code: 例如,如果您想从日期字符串中获取一年,则可以编写下一个代码:

$date = 'November 18, 2009, 3:00PM';

$year = date('Y', strtotime($date));

Or, if you want to know how much days in the month in date you get, you could write such code: 或者,如果您想知道您获得的月份中的天数,您可以编写以下代码:

$date = 'November 18, 2009, 3:00PM';

$num_of_days = date('t', strtotime($date));

't' returns the number of days in the given month. 't'返回给定月份的天数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM