【问题标题】:How to convert yyyymm to mmyyyy in php如何在php中将yyyymm转换为mmyyyy
【发布时间】:2018-06-29 12:08:39
【问题描述】:

我有这个日期(年和月)201511,我需要以这种格式显示:112015(月和年)。

我试过这个:date('m/Y', strtotime($date)),但不起作用。

【问题讨论】:

标签: php


【解决方案1】:

您必须以您拥有的格式阅读并正确阅读。 date('m/Y') 不是您输入该函数的格式。

阅读 http://php.net/manual/datetime.createfromformat.php

http://php.net/manual/function.date.php,如果你真的必须使用date()

m 和 n |一个月的数字表示,带或不带前导零 | 01 到 12 或 1 到 12

是的 |一年的完整数字表示,4 位数字 |示例:1999 年或 2003 年

$dateStringOldFormat = '201511';
$dateStringNewFormat = DateTime::createFromFormat('Ym', $dateStringOldFormat)->format('mY');

【讨论】:

  • 请确保您链接到英文 php.net,因为这是英文 StackOverflow,并且对于不了解英文的人还有其他语言可用:)
  • 啊抱歉它总是重定向到德语页面,因为它是我的语言环境...我会更正它
  • 你也可以使用没有语言部分的链接php.net/manual/datetime.createfromformat.php,它会重定向到用户的语言环境
【解决方案2】:

如果是我,我会使用一些字符串工具来获取值。

演示:https://3v4l.org/1LMVj

$d = 201511;

$year = substr($d,0,4);
$month = substr($d,-2);

$reverse = $month.$year;
echo $reverse;
// 112015

【讨论】:

  • 抱歉,它是一个“。”在 php 中用于字符串 concat - 已经有一段时间了。
  • @steros prob right :) - 因此我赞成你的回答!
  • 在发布之前测试您的代码是个好主意。我推荐3v4l.org 这样你可以看到你不需要连接一个空字符串。
【解决方案3】:

如果您有完整日期。转换很简单。 否则在这种格式下你可以使用这种方法。

echo dateFormat('201511'); // Your Format


function dateFormat($input){
$date=substr($input, 0,4).'/'.substr($input, 4,5).'/13'; // add extra date grater than 12
return date('mY',strtotime($date));// convert and return
}

谢谢。

【讨论】:

  • 如果您要使用两次substr(),为什么还要使用str_to_time()date
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
相关资源
最近更新 更多