PHP에서 숫자를 월 이름으로 변환
이 PHP 코드가 있습니다 :
$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", strtotime($monthNum));
echo $monthName;
하지만 December
오히려 돌아오고 August
있습니다.
$result["month"]
는 8과 같으므로 sprintf
함수에 a 0
를 추가 하여 만듭니다 08
.
권장되는 방법은 다음과 같습니다.
요즘에는 날짜 / 시간 계산에 DateTime 객체를 사용해야합니다. 이를 위해서는 PHP 버전> = 5.2가 필요합니다. Glavić의 답변에 표시된 것처럼 다음을 사용할 수 있습니다.
$monthNum = 3;
$dateObj = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F'); // March
!
서식 문자는 받는 사람 모두 재설정하는 데 사용되는 유닉스 시대를 . m
형식 문자는 앞에 0이있는 달의 숫자 표현입니다.
대체 솔루션 :
이전 PHP 버전을 사용하고 있는데 현재 업그레이드 할 수없는 경우이 솔루션을 사용할 수 있습니다. date()
function 의 두 번째 매개 변수는 타임 스탬프를 허용하며 다음 mktime()
과 같이 만들 수 있습니다 .
$monthNum = 3;
$monthName = date('F', mktime(0, 0, 0, $monthNum, 10)); // March
같은 3 문자 월 이름을 원하면로 Mar
변경 F
하십시오 M
. 사용 가능한 모든 포맷 옵션 목록은 PHP 매뉴얼 문서 에서 찾을 수 있습니다 .
모든 사람이 strtotime () 및 date () 함수를 사용하고 있기 때문에 DateTime 예제 를 보여줍니다 .
$dt = DateTime::createFromFormat('!m', $result['month']);
echo $dt->format('F');
사용 mktime()
:
<?php
$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
echo $monthName; // Output: May
?>
PHP 매뉴얼을 참조하십시오 : http://php.net/mktime
strtotime
표준 날짜 형식을 예상하고 타임 스탬프를 다시 전달합니다.
strtotime
날짜 형식을 출력하기 위해 한 자릿수를 전달 하는 것 같습니다 .
mktime
날짜 요소를 매개 변수 로 사용 하는 것을 사용해야합니다 .
전체 코드 :
$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", mktime(null, null, null, $monthNum));
echo $monthName;
그러나 mktime 함수는 월 번호 앞에 0을 필요로하지 않으므로 첫 번째 행은 완전히 필요하지 않으며 $result["month"]
함수에 바로 전달 될 수 있습니다.
그러면 날짜를 인라인으로 반향하여 모두 한 줄로 결합 할 수 있습니다.
리팩토링 된 코드 :
echo date("F", mktime(null, null, null, $result["month"], 1));
...
현재 로케일과 관련하여 변환을 수행하려면 다음 strftime
기능을 사용할 수 있습니다 .
setlocale(LC_TIME, 'fr_FR.UTF-8');
$monthName = strftime('%B', mktime(0, 0, 0, $monthNumber));
date
로케일을 존중하지 않습니다 strftime
.
연도의 시작에서 끝까지 달 이름 배열을 원한다면 드롭 다운 선택을 채우려면 다음을 사용하십시오.
for ($i = 0; $i < 12; ++$i) {
$months[$m] = $m = date("F", strtotime("January +$i months"));
}
월 번호가있는 경우, 기본 날짜가 1 일이고 현재 연도의 기본 연도가있는 날짜를 먼저 작성한 다음 작성된 날짜에서 월 이름을 추출하십시오.
echo date("F", strtotime(date("Y") ."-". $i ."-01"))
이 코드는 월 번호가 $ i에 저장되어 있다고 가정합니다.
이것이 누군가를 돕기를 바랍니다.
주어진 숫자에서 한 달을 인쇄하는 방법은 여러 가지가 있습니다. 하나의 스위트 룸을 선택하십시오.
1. 매개 변수 'F'와 함께 date () 함수
코드 예 :
$month_num = 10;
echo date("F", mktime(0, 0, 0, $month_num, 10)); //output: October
2. createFromFormat ()을 사용하여 PHP 날짜 객체를 생성
코드 예
$dateObj = DateTime::createFromFormat('!m', $monthNum);
echo "month name: ".$dateObj->format('F'); // Output: October
3. strtotime () 함수
echo date("F", strtotime('00-'.$monthNum.'-01')); // Output: October
4. mktime () 함수
echo date("F", mktime(null, null, null, $monthNum)); // Output: October
5. jdmonthname ()을 사용하여
$jd=gregoriantojd($monthNum,10,2019);
echo jdmonthname($jd,0); // Output: Oct
$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
나는 https://css-tricks.com/snippets/php/change-month-number-to-month-name/ 에서 이것을 발견 했으며 완벽하게 작동했습니다.
필요에 따라 적응
$m='08';
$months = array (1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'May',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Oct',11=>'Nov',12=>'Dec');
echo $months[(int)$m];
이것은 쉬운 일이 아닙니다. 왜 그렇게 많은 사람들이 그런 나쁜 제안을합니까? @Bora가 가장 가까웠지만 가장 강력합니다.
/***
* returns the month in words for a given month number
*/
date("F", strtotime(date("Y")."-".$month."-01"));
이것은 그것을하는 방법입니다
Am currently using the solution below to tackle the same issue:
//set locale,
setlocale(LC_ALL,"US");
//set the date to be converted
$date = '2016-08-07';
//convert date to month name
$month_name = ucfirst(strftime("%B", strtotime($date)));
echo $month_name;
To read more about set locale go to http://php.net/manual/en/function.setlocale.php
To learn more about strftime go to http://php.net/manual/en/function.strftime.php
Ucfirst()
is used to capitalize the first letter in a string.
Just one line
DateTime::createFromFormat('!m', $salary->month)->format('F'); //April
You need set fields with strtotime
or mktime
echo date("F", strtotime('00-'.$result["month"].'-01'));
With mktime
set only month. Try this one:
echo date("F", mktime(0, 0, 0, $result["month"], 1));
date("F", strtotime($result["month"]))
use the above code
<?php
$month =1;
$convert =DateTime::createFromFormat('!m', $month);
echo $convert->format('F');
?>
I think using cal_info() is the easiest way to convert from number to string.
$monthNum = sprintf("%02s", $result["month"]); //Returns `08`
$monthName = cal_info(0); //Returns Gregorian (Western) calendar array
$monthName = $monthName[months][$monthNum];
echo $monthName; //Returns "August"
See the docs for cal_info()
Use:
$name = jdmonthname(gregoriantojd($monthNumber, 1, 1), CAL_MONTH_GREGORIAN_LONG);
I know this question was asked a while ago now, but I figured everyone looking for this answer was probably just trying to avoid writing out the whole if/else statements, so I wrote it out for you so you can copy/paste. The only caveat with this function is that it goes on the actual number of the month, not a 0-indexed number, so January = 1, not 0.
function getMonthString($m){
if($m==1){
return "January";
}else if($m==2){
return "February";
}else if($m==3){
return "March";
}else if($m==4){
return "April";
}else if($m==5){
return "May";
}else if($m==6){
return "June";
}else if($m==7){
return "July";
}else if($m==8){
return "August";
}else if($m==9){
return "September";
}else if($m==10){
return "October";
}else if($m==11){
return "November";
}else if($m==12){
return "December";
}
}
This for all needs of date-time converting
<?php
$newDate = new DateTime('2019-03-27 03:41:41');
echo $newDate->format('M d, Y, h:i:s a');
?>
To get month name by providing month number
$month_number = 5;
$monthName = date('F', mktime(0, 0, 0, $month_number, 10));
Where 'F' will return you month name Eg. 'May'
This is how I did it
// sets Asia/Calcutta time zone
date_default_timezone_set("Asia/Calcutta");
//fetches current date and time
$date = date("Y-m-d H:i:s");
$dateArray = date_parse_from_format('Y/m/d', $date);
$month = DateTime::createFromFormat('!m', $dateArray['month'])->format('F');
$dateString = $dateArray['day'] . " " . $month . " " . $dateArray['year'];
echo $dateString;
returns 30 June 2019
You can just use monthname() function in SQL.
SELECT monthname(date_column) from table group by monthname(date_column)
for php 7.1
$monthyear= date("M Y");
Use a native function such as jdmonthname()
:
echo jdmonthname($monthNum, CAL_MONTH_GREGORIAN_LONG);
참고URL : https://stackoverflow.com/questions/18467669/convert-number-to-month-name-in-php
'development' 카테고리의 다른 글
Rails after_save 콜백에서 변경된 속성을 결정 하시겠습니까? (0) | 2020.06.24 |
---|---|
Runtime.getRuntime (). totalMemory () 및 freeMemory () 란 무엇입니까? (0) | 2020.06.24 |
몽구스에서 날짜별로 어떻게 정렬합니까? (0) | 2020.06.24 |
PHP에서 데이터베이스에 액세스 할 수있는 싱글 톤의 사용 사례가 있습니까? (0) | 2020.06.24 |
Java에서 두 버전 문자열을 어떻게 비교합니까? (0) | 2020.06.24 |