PHP > Tips > PHPで日付整形

2019年6月12日公開(2020年5月12日更新)

やりたいこと

日付のデータを整形する。

正しい日付

2019-06-12

4桁の年、2桁の月、2桁の日が「-」(ハイフン、マイナス記号)で連結されている形にしたい。

不完全な日付

2019

4桁の年だけ。月と日が欠落している。

2019-06

4桁の年と2桁の月だけ。日が欠落している。

自作関数

不完全な日付データを正しい日付データの形に整える関数を自作してみよう。
欠落している月や日は、とりあえず1月や1日にしておく。

#code(php){{

?php

/**

* format date
* 2019-06-12
*
* @param  string
* @return string
*/

function format_date($date = NULL)
{

   // split string
   $element = explode('-', $date); // 2019-06-12
   $year  = (int)@$element[0]; // 2019
   $month = (int)@$element[1]; // 06
   $day   = (int)@$element[2]; // 12
   // set default value
   if ($year == 0) $year = 1;
   if ($month == 0) $month = 1;
   if ($day == 0) $day = 1;
   // format with PHP DateTime Class
   $d = new DateTime();
   $d->setDate($year, $month, $day);
   $format_date = $d->format('Y-m-d');
   return $format_date;

}
?>
}}

実行例(PHP Version 7.2.13)

2019-06-12 -> 2019-06-12
2019-06 -> 2019-06-01
2019 -> 2019-01-01
1234-56-78 -> 1238-10-17
2000-01-32 -> 2000-02-01
2000-13-01 -> 2001-01-01
9999-9999-9999 -> 10859-07-16
(空白) -> 0001-01-01
0 -> 0001-01-01
1 -> 0001-01-01
2 -> 0002-01-01
1901 -> 1901-01-01
1902 -> 1902-01-01
1755 -> 1755-01-01
1755-09 -> 1755-09-01
1755-09-28 -> 1755-09-28
1902 -> 1902-01-01
4-5-6 -> 0004-05-06
a-b-c -> 0001-01-01

参考

自作関数 その2

UTCや年月日などの表記にも対応できるように少し改良。

#code(php){{{

?php

/**

* format date
* 2020-05-17
*
* @param string $date
* @return string $date_format
*/

function format_date($date = "")
{

   # UTC : split date + "T" + time
   $element = explode('T', $date); # 1976T => [1976, T]
   $date_part = $element[0]; # 1976
   # 年月日: replace to "-" 1976年8月1日 => 1976-8-1-
   $unit = array("年", "月", "日");
   $date_part = str_replace($unit, "-", $date_part);
   # split Y + m + d
   $YMD = explode('-', $date_part);
   $year  = (int) @$YMD[0]; # 1976
   $month = (int) @$YMD[1]; # 08
   $day   = (int) @$YMD[2]; # 01
   # 数字以外を除去 1976年 → 1976
   $year = preg_replace('/[^0-9]/', '', $year);
   $month = preg_replace('/[^0-9]/', '', $month);
   $day = preg_replace('/[^0-9]/', '', $day);
   # default date
   $year_start = 1;
   $month_start = 1;
   $day_start = 1;
   if ($year < 1) {
       $year = $year_start;
   }
   if ($month < 1) {
       $month = $month_start;
   }
   if ($day < 1) {
       $day = $day_start;
   }
   # format
   $format = "Y-m-d";
   $date_comp = $year . "-" . $month . "-" . $day; # compose Y-m-d
   $d = DateTime::createFromFormat($format, $date_comp);
   $date_format = $d->format($format);
   return $date_format;

}
}}}

参考

日時の形式を検証する関数

#code(php){{{

?php

/**

* validation datetime format
*
* @param string $date
* @param string $format
* @return bool
*/

function validateDate($date, $format = 'Y-m-d H:i:s')
{

   $d = DateTime::createFromFormat($format, $date);
   return $d && $d->format($format) == $date;

}
}}}

これは便利ですね。


トップ   編集 凍結 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019-06-12 (水) 07:35:15