php 如何从完整的“日期”字符串中仅提取“天”值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4275599/
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-25 12:30:19  来源:igfitidea点击:

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

phpdate

提问by Hyman Roscoe

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?

我有一个格式为'Y-m-d'. 我想遍历数组,只提取'd'每个成员的日期 ( ),但无法弄清楚如何拆分它。我是否以某种方式使用子字符串?

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.

简单地说,我有'2010-11-24',我想从中得到'24'。问题是一天可能是个位数或两位数。

回答by Pekka

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

如果您的 PHP < 5.3,请使用strtotime()

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

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

如果您的 PHP >= 5.3,请使用DateTime基于createFromFormat的解决方案-DateTime是未来,可以处理 1900 年和 2038 年以后的日期:

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

回答by jensgram

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

Demo, docs on explode().

演示,文档explode()

Or even

甚至

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

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

演示、文档substr()strrpos().

Disclaimer: Both are oldschool!

免责声明:两者都是老派!

回答by kenorb

Try using date_parse_from_format, e.g.:

尝试使用date_parse_from_format,例如:

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

回答by Marek Augustyn

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

回答by martynthewolf

<?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);

?>

回答by Frank Mu?oz

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

回答by njoshsn

$dt = "2008/02/23";

$dt = "2008/02/23";

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

echo '今天是'。日期("d", strtotime($dt));