【问题标题】:How can I get year month and day from a string of numbers?如何从一串数字中获取年月日?
【发布时间】:2011-12-13 03:04:37
【问题描述】:

我有一个以20111213 (YYYYMMDD) 形式提供给我的日期,我正在尝试将这些部分分成日、月和年。我正在使用此代码:

$day = substr($string, 6, 8);
$month = substr($string, 4, 6);
$year = substr($string, 0, 4);
$final = $day . "-" . $month . "-" . $year;
echo $final;

但这给了我输出

13-1213-2011

如您所见,月份被解释为 4 个字符,我无法仅输出 12 个字符。为帮助干杯。

【问题讨论】:

  • 我知道这并不完全相关,但也请看一下:php.net/manual/en/function.date-parse.php like: date_parse("20111213") 可以满足您的需求!
  • 通常最好在将日期转换为字符串之前尽可能长时间地保留日期。使用DateTime,如下面我的回答。

标签: php date substr


【解决方案1】:

您误用了第三个参数。它是所需的子字符串的长度,而不是结束位置:

$day = substr($string, 6, 2);    // 2 char substring
$month = substr($string, 4, 2);  // 2 char substring
$year = substr($string, 0, 4);   // 4 char substring

$final = $day . "-" . $month . "-" . $year;
echo $final;
// 13-12-2011

See the documentation 正确使用。

【讨论】:

  • 谢谢,这有效,但我需要等待 10 分钟才能将其标记为已批准的答案。
【解决方案2】:

阅读手册substr,第三个参数为$length

【讨论】:

    【解决方案3】:

    使用

            $string = "20111213";
            $day = substr($string, 6, 2);
            $month = substr($string, 4, 2);
            $year = substr($string, 0, 4);
            $final = $day . "-" . $month . "-" . $year;
            echo $final;
    

    【讨论】:

      【解决方案4】:

      试试这个

      var_dump(date('Y M d', strtotime('20111213')));
      

      输出:-

      '2011 年 12 月 13 日'

      您可以使用格式字符串随意修改输出。

      http://www.php.net/date
      http://www.php.net/strtotime

      或者:-

      $date = new DateTime('20111213');
      $year = $date->format('Y');
      $month = $date->format('M');
      $day = $date->format('d');
      echo "$year $month $day";
      

      输出:-

      2011 年 12 月 13 日

      http://www.php.net/datetime

      在所有这些示例中,将格式字符串中的“M”替换为“m”以获得“12”而不是“Dec”。

      如果您正在寻找此输出“2011-12-13”,请使用

      $date = new DateTime('20111213');
      echo $date->format('Y-m-d');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-02
        • 2018-08-30
        • 2020-12-19
        • 1970-01-01
        • 1970-01-01
        • 2015-09-06
        相关资源
        最近更新 更多