0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

datetimeを配列にしたり、一行で日付だけ受け取ったり

Posted at

やりたいこと

'2019-10-09 01:20:33'

というmysqlに登録されているdatetime形式のデータを

$datetime = [
    'year' => '2019',
    'month' => '10',
    'day' => '09',
    'hour' => '01',
    'minute' => '20',
    'second' => '33',
];

といった配列形式にしたり

$day = hogehoge('2019-10-09 01:20:33'); // 09

と、ぱっと取得できるようにしたい。

配列形式にする

// 一般的なdatetime
$datetime1 = getDateTimeArray('2019-10-09 01:20:33');
$datetime2 = getDateTimeArray('2019/10/09 01:20:33');

// 特殊な場合はformatオプションを付ける
$datetime3 = getDateTimeArray('2019年10月09日01時20分33秒', 'Y年m月d日H時i分s秒');

function getDateTimeArray($datetime, $format = '')
{
    if (empty$format) {
        $date = new DateTime($datetime);
    } else {
        $date= DateTime::createFromFormat($datetime, $format);        
    }
    $datetime_key = ['year', 'month', 'day', 'hour', 'minute', 'second'];
    return array_combine(
        $datetime_key,
        preg_split('/[-: ]/', $date->format('Y-m-d H:i:s'))
    );
}

日付だけほしい

// 一行で
$day1 = date_create('2019-10-09 01:20:33')->format('d');

$day2 = DateTime::createFromFormat('Y年m月d日H時i分s秒', '2019年10月09日01時20分33秒')->format('d');

関数使ったほうが見やすいかな

// 一般的なdatetime
$day1 = getDateTimeByFormat('2019-10-09 01:20:33', 'd');

// 特殊な場合
$day2 = getDateTimeByFormat('2019年10月09日01時20分33秒', 'd', 'Y年m月d日H時i分s秒');

function getDateTimeByFormat($datetime, $format, $create_format = "")
{
    if (empty($create_format)) {
        return date_create($datetime)->format($format);
    } else {
        return DateTime::createFromFormat($create_format, $datetime)->format($format);
    }
}

日付以外表示しないならこれでもいいがちょっと長い。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?