php 将月份编号转换为月份简称

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

Convert month number to month short name

php

提问by Elitmiar

I have a variable with the following value

我有一个具有以下值的变量

$month = 201002; 

the first 4 numbers represent the year, and the last 2 numbers represent the month. I need to get the last 2 numbers in the month string name eg. Feb

前4个数字代表年份,后2个数字代表月份。我需要获取月份字符串名称中的最后 2 个数字,例如。二月

My code looks like this

我的代码看起来像这样

<?php echo date('M',substr($month,4,6)); ?>

I can I go about to obtain the month name

我可以去获取月份名称吗

回答by mexique1

Append "01" and strtotime will be able to parse the string :

附加“01”和 strtotime 将能够解析字符串:

echo date('M', strtotime($month . '01'));

回答by r3zn1k

The second parameter of date is a timestamp. Use mktimeto create one.

日期的第二个参数是时间戳。使用mktime创建一个。

$month = 201002;
$monthNr = substr($month, -2, 2);

$timestamp = mktime(0, 0, 0, $monthNr, 1);
$monthName = date('M', $timestamp );

回答by Gaurav Porwal

This may help you..

这可能会帮助你..

  $month = substr($month, -2, 2);
  echo date('M', strtotime(date('Y-'. $month .'-d'))); 

回答by Hossam Ghareeb

You can use the DateTime Class to get a Date data structure using date string and format. Then get a date string with any format like this:

您可以使用 DateTime 类来获取使用日期字符串和格式的日期数据结构。然后获取任何格式的日期字符串,如下所示:

$month = 201002; 
$date = DateTime::createFromFormat('Yd', $month);  
$monthName = $date->format('M'); // will get Month name

回答by OlimilOops

$mydate = "201002";
date('M', mktime(0, 0, 0, substr($mydate, 4, 2), 1, 2000)); 

回答by Your Common Sense

Being a programmer, and even knowing nothing of PHP data magic, I'd made it

作为一名程序员,甚至对 PHP 数据魔法一无所知,我做到了

$month = intval(substr($input_date,4,2));
$mons = explode(" ","Zer Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
echo $mons[$month];