How to extract only 'Day' value from full 'Date' string?

不想你离开。 提交于 2021-02-04 09:57:05

问题


I have an array of Date values in the format of 'Y-m-d'. I want to loop over the array and only extract the day ('d') of each member, but can't figure out to split it. Do I use substrings in some way?

Put simply, I have '2010-11-24', and I want to get just '24' from that. The problem being the day could be either single or double figures.


回答1:


If you have PHP < 5.3, use strtotime():

$string = "2010-11-24";
$timestamp = strtotime($string);
echo date("d", $timestamp);

If you have PHP >= 5.3, use a DateTime based solution using createFromFormat - DateTime is the future and can deal with dates beyond 1900 and 2038:

 $string = "2010-11-24";
 $date = DateTime::createFromFormat("Y-m-d", $string);
 echo $date->format("d");



回答2:


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

Demo, docs on explode().

Or even

$date = '2010-11-24';
$d = substr($date, strrpos($date, '-') + 1);

Demo, docs on substr() and strrpos().

Disclaimer: Both are oldschool!




回答3:


Try using date_parse_from_format, e.g.:

date_parse_from_format('Y-m-d', '2010-11-24')['day'];

Testing in shell:

$ php -r "echo date_parse_from_format('Y-m-d', '2010-11-24')['day'];"
24



回答4:


php> $d = '2010-11-24';
'2010-11-24'
php> $fields = explode('-', $d);
array (
  0 => '2010',
  1 => '11',
  2 => '24',
)
php> $fields[2];
'24'



回答5:


<?php

$dates = array('2010-01-01', '2010-01-02', '2010-01-03', '2010-01-23');

foreach ($dates as $date) {
    $day[] = substr($date, 8, 2);
}

var_dump($day);

?>



回答6:


$string = "2010-11-24";
$date = new DateTime($string);
echo date_format($date, 'd');



回答7:


$dt = "2008/02/23";

echo 'The day is '. date("d", strtotime($dt));



来源:https://stackoverflow.com/questions/4275599/how-to-extract-only-day-value-from-full-date-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!