programing

PHP에서 숫자를 월 이름으로 변환

itsource 2022. 9. 21. 21:24
반응형

PHP에서 숫자를 월 이름으로 변환

PHP 코드는 다음과 같습니다.

$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", strtotime($monthNum));

echo $monthName;

다시 있다DecemberAugust.

$result["month"]에 8은 8입니다.sprintf는 A를 입니다.0을 가능하게 하다08.

이를 위해 권장되는 방법은 다음과 같습니다.

요즘은 날짜/시간 계산에 Date Time 개체를 사용해야 합니다.이를 위해서는 PHP 버전이 > = 5.2여야 합니다.글라비치의 답변에 나타난 바와 같이 다음을 사용할 수 있습니다.

$monthNum  = 3;
$dateObj   = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F'); // March

포맷 문자는 모든 것을 Unix Epoch로 리셋하기 위해 사용됩니다.m포맷 문자입니다.

대체 솔루션:

이전 버전의 PHP를 사용하고 있으며 현재 업그레이드할 수 없는 경우 이 솔루션을 사용할 수 있습니다.함수의 두 번째 파라미터는 타임스탬프를 받아들이기 때문에 다음과 같이 타임스탬프를 작성할 수 있습니다.

$monthNum  = 3;
$monthName = date('F', mktime(0, 0, 0, $monthNum, 10)); // March

의 월명을 Mar, 변경F로로 합니다.M사용 가능한 모든 포맷옵션 목록은 PHP 매뉴얼 매뉴얼에 기재되어 있습니다.

모두가 strtotime() 및 date() 함수를 사용하고 있다고 해서 Date Time의 예를 제시하겠습니다.

$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

로케일을 하려면 , 「 」를 합니다.strftime★★★★

setlocale(LC_TIME, 'fr_FR.UTF-8');                                              
$monthName = strftime('%B', mktime(0, 0, 0, $monthNumber));

date하지 않습니다.strftime

strtotime 는 표준 날짜 형식을 예상하고 타임스탬프를 반환합니다.

날짜 형식을 출력하기 위해 한 자리 숫자를 전달하고 있는 것 같습니다.

날짜 요소를 매개 변수로 사용하는 방법을 사용해야 합니다.

풀코드:

$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", mktime(null, null, null, $monthNum));

echo $monthName;

는 월에 첫 행은 불필요합니다.또, mktime은 0으로 되어 있습니다.$result["month"]을 사용법

이 모든 것을 1줄로 조합하여 날짜를 인라인으로 에코할 수 있습니다.

리팩터 코드:

echo date("F", mktime(null, null, null, $result["month"], 1));

...

예를 들어 드롭다운 선택 항목을 입력하는 등 연초부터 말까지의 월 이름 배열만 원하는 경우 다음을 사용합니다.

for ($i = 0; $i < 12; ++$i) {
  $months[$m] = $m = date("F", strtotime("January +$i months"));
}

지정된 숫자에서 한 달을 인쇄하는 방법은 여러 가지가 있습니다.스위트룸을 1개 선택해 주세요.

1. date() 함수와 파라미터 'F'

코드 예:

$month_num = 10;
echo date("F", mktime(0, 0, 0, $month_num, 10)); //output: October

2. createFromFormat()을 사용하여 php date 객체를 작성한다.

코드 예시

$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

월 번호가 있는 경우 먼저 해당 월 번호에서 기본 날짜인 1 및 현재 연도를 사용하여 날짜를 작성한 날짜에서 월 이름을 추출할 수 있습니다.

echo date("F", strtotime(date("Y") ."-". $i ."-01"))

이 코드는 월 번호가 $i에 저장되어 있다고 가정합니다.

$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];

필드 설정 필요:strtotime또는mktime

echo date("F", strtotime('00-'.$result["month"].'-01'));

와 함께mktime월만 설정하다이것을 사용해 보세요.

echo date("F", mktime(0, 0, 0, $result["month"], 1));

이것은 매우 쉽다, 왜 그렇게 많은 사람들이 나쁜 제안을 하는 것일까?@Bora가 가장 가까웠지만 이것이 가장 견고하다.

/***
 * returns the month in words for a given month number
 */
date("F", strtotime(date("Y")."-".$month."-01"));

이것이 그것을 하는 방법이다

현재 다음 솔루션을 사용하여 동일한 문제를 해결하고 있습니다.

//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;

set local에 대한 자세한 내용은 http://php.net/manual/en/function.setlocale.php를 참조하십시오.

strftime에 대한 자세한 내용은 http://php.net/manual/en/function.strftime.php를 참조하십시오.

Ucfirst()는 문자열의 첫 글자를 대문자로 표시하기 위해 사용됩니다.

이것은 날짜-시간 변환의 모든 요구에 대응합니다.

 <?php
 $newDate = new DateTime('2019-03-27 03:41:41');
 echo $newDate->format('M d, Y, h:i:s a');
 ?>

이 작업은 한 줄로만 수행할 수 있습니다.

DateTime::createFromFormat('!m', $salary->month)->format('F'); //April
$days = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
$month = ( date('m') < 10 ) ? date('m')[1] : date('m');

월을 추출합니다.

숫자에서 문자열로 변환하려면 cal_info()를 사용하는 것이 가장 쉬운 방법이라고 생각합니다.

$monthNum = sprintf("%02s", $result["month"]); //Returns `08`
$monthName = cal_info(0); //Returns Gregorian (Western) calendar array
$monthName = $monthName[months][$monthNum];

echo $monthName; //Returns "August"

cal_info()에 대해서는 문서를 참조해 주세요.

나는 이렇게 했다.

// 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;

돌아온다30 June 2019

여기서 간단한 트릭은 필요에 따라 사용할 수 있는 strtotime() 함수를 사용하여 숫자를 월 이름으로 변환할 수 있습니다.

1. 1월, 2월, 3월 결과를 원하는 경우 아래 날짜 안에 'M'을 파라미터로 하여 시험해 보십시오.

$month=5;
$nmonth = date('M',strtotime("01-".$month."-".date("Y")));
echo $nmonth;

출력 : 5월

/2. 'M'이 아닌 'F'를 사용하여 1월 3월 등의 출력으로 보름달 이름을 얻을 수 있습니다.

$month=1;
$nmonth = date('M',strtotime("01-".$month."-".date("Y")));
echo $nmonth;

출력: 1월

이것은 LC_에 관한 것입니다.시간을

$date = new DateTime('2022-04-05');
$mes = strftime('%B', $date->getTimestamp());

나의 접근법

$month = date('m');
$months_of_year = array(
    array('month' => '01', 'translation' => 'janeiro'),
    array('month' => '02', 'translation' => 'fevereiro'),
    array('month' => '03', 'translation' => 'março'),
    array('month' => '04', 'translation' => 'abril'),
    array('month' => '05', 'translation' => 'maio'),
    array('month' => '06', 'translation' => 'junho'),
    array('month' => '07', 'translation' => 'julho'),
    array('month' => '08', 'translation' => 'agosto'),
    array('month' => '09', 'translation' => 'setembro'),
    array('month' => '10', 'translation' => 'outubro'),
    array('month' => '11', 'translation' => 'novembro'),
    array('month' => '12', 'translation' => 'dezembro'),
);
$current_month = '';
foreach ($months_of_year as $key => $value) 
{
    if ($value['month'] == $month){
        $current_month = $value['translation'];  
        break;  
    }
}
echo("mes:" . $current_month);

용도:

$name = jdmonthname(gregoriantojd($monthNumber, 1, 1), CAL_MONTH_GREGORIAN_LONG);

언급URL : https://stackoverflow.com/questions/18467669/convert-number-to-month-name-in-php

반응형