Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
75.00% covered (success)
75.00%
3 / 4
CRAP
95.24% covered (success)
95.24%
20 / 21
Date
0.00% covered (danger)
0.00%
0 / 1
75.00% covered (success)
75.00%
3 / 4
11
95.24% covered (success)
95.24%
20 / 21
 isDateString
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
7 / 7
 isDateTimeString
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
7 / 7
 getAge
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getAgeByString
0.00% covered (danger)
0.00%
0 / 1
2.03
80.00% covered (success)
80.00%
4 / 5
<?php
namespace Puyo\Util;
/**
 * 日付関連ユーティリティ
 * @version 1.0.0
 */
class Date
{
    /**
     * 日付文字列として有効か否かを返す (YYYY-mm-dd)
     * @param string $str
     * @return bool
     */
    public static function isDateString($str) {
        if(1 !== preg_match('/\A\d{4}-\d{2}-\d{2}\z/u', $str)) {
            return false;
        }
        if(false === ($intTime = strtotime($str))) {
            return false;
        }
        if($str !== date('Y-m-d', $intTime)) {
            return false;
        }
        return true;
    }
    /**
     * 日付時刻文字列として有効ない中を返す (YYYY-mm-dd HH:ii:ss)
     * @param string $str
     * @return bool
     */
    public static function isDateTimeString($str) {
        if(1 !== preg_match('/\A\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\z/u', $str)) {
            return false;
        }
        if(false === ($intTime = strtotime($str))) {
            return false;
        }
        if($str !== date('Y-m-d H:i:s', $intTime)) {
            return false;
        }
        return true;
    }
    /**
     * 誕生日から年齢を返す
     * @param \DateTime $dtBirthday
     * @param \DateTime|null $dtToday (optional)
     * @return int 年齢
     */
    public static function getAge(\DateTime $dtBirthday, \DateTime $dtToday=null) {
        $result = $dtToday->diff($dtBirthday)->y;
        return $result;
    }
    /**
     * 誕生日から年齢を返す
     * @param string $strBirthday
     * @param string|null $strToday (optional)
     * @return int 年齢
     */
    public static function getAgeByString($strBirthday, $strToday) {
        $dtBirthday = new \DateTime($strBirthday);
        if($strToday === null) {
            $strToday = (new \DateTime())->format('Y-m-d');
        }
        $dtToday = new \DateTime($strToday);
        return static::getAge($dtBirthday, $dtToday);
    }
}