PHP convert dates with DateTime examples

Categorías: 

Etiquetas: 

/**
 * DateHelper class
 *
 */
class DateHelper
{
    private $LC_TIME;
 
    /**
     * 
     * @param string $timezone [optional] default timezone
     * @param string $LC_TIME [optional] default language for string date format
     */
    public function __construct($timezone = "Europe/Madrid", $LC_TIME = 'es_ES')
    {
        date_default_timezone_set($timezone);
        $this->LC_TIME = $LC_TIME;
    }
 
    /**
     * Convert Date/Datetime to MySQL format (Y-m-d H:i:s)
     * @param string $date
     * @param string $format [optional] d/m/Y | d/m/Y H:i | d/m/Y H:i:s
     * @param string $separator [optional] '/'
     * @return string|null Date in format Y-m-d (H:i:s) or <b>NULL</b>
     */
    public function DateConvert($date, $format = 'd/m/Y', $separator = '/')
    {
        $finalDate = null;
        $datePreFilter = str_replace($separator, '-', $date);
 
        switch ($format) {
            case 'd/m/Y':
                if ($this->isValidDate($datePreFilter, $format, $separator)) {
                    $oDate = new \DateTime($datePreFilter);
                    $finalDate = $oDate->format('Y-m-d');
                }
                break;
 
            case 'd/m/Y H:i':
                $auxDate = explode(' ', $datePreFilter);
                if (isset($auxDate[0]) && isset($auxDate[1])) {
                    $arrayDate = explode('-',$auxDate[0]);
                    $hourMinute = $auxDate[1];
 
                    if ($this->isValidDate($auxDate[0]) &&
                            $this->isValidHour($hourMinute, 'H:i')) {
                        $oDate = new \DateTime($datePreFilter . ':00');
                        $finalDate = $oDate->format('Y-m-d H:i:s');
                    }
                }
                break;
            case 'd/m/Y H:i:s':
                $auxDate = explode(' ', $datePreFilter);
                if (isset($auxDate[0]) && isset($auxDate[1])) {
                    $arrayDate = explode('-',$auxDate[0]);
                    $hourMinute = $auxDate[1];
 
                    if ($this->isValidDate($auxDate[0]) && 
                        $this->isValidHour($hourMinute, 'H:i:s')) {
                        $oDate = new \DateTime($datePreFilter);
                        $finalDate = $oDate->format('Y-m-d H:i:s');
                    }
                }
                break;
        }
 
        return $finalDate;
    }
 
    /**
     * Transform a Y-m-d date to another format (short|medium|large). Eg: <br>
     * short: 20-11-2014 <br>
     * medium: 20 Noviembre 2014 <br>
     * large: Jueves, 20 de Noviembre 2014
     * 
     * @param string $date
     * @param string $formatType [optional] short|medium|large
     * @param string $originalFormat [optional] 
     * @param string $time [optional] print H:i:s
     * @return string
     */
    public function DateFormat($date, $formatType = 'medium', $originalFormat = 'Y-m-d', $time = false)
    {
        setlocale(LC_TIME, $this->LC_TIME);
 
        $dateFormatted = $date;
 
        if ($this->isValidDate($date, $originalFormat, '-')) {
            $oDate = new \DateTime($date);
            switch ($formatType) {
                case 'short':
                    $format = $time ? "%d/%m/%Y %H:%M:%S" : "%d-%m-%Y";
                    $dateFormatted = strftime($format, $oDate->getTimestamp());
                    break;
                case 'large':
                    $format = $time ? "%A, %d de %B %Y %H:%M:%S" : "%A, %d de %B %Y";
                    $dateFormatted = strftime($format, $oDate->getTimestamp());
                    break;
                case 'medium':
                default:
                    $format = $time ? "%d %B %Y %H:%M:%S" : "%d %B %Y";
                    $dateFormatted = strftime($format, $oDate->getTimestamp());
                    break;
            }
        }
        return $dateFormatted;
    }
 
 
    /**
     * Checks for a valid date by format and separator
     * 
     * @param string $date
     * @param string $originalFormat [optional] d/m/Y | d/m/Y H:i | d/m/Y H:i:s
     * @param string $separator [optional] '/'
     * @return boolean
     */
    public function isValidDate($date, $originalFormat = 'd/m/Y', $separator = '/')
    {
        $isValidDate = false;
 
        $datePreFilter = str_replace($separator, '-', $date);
        switch ($originalFormat) {
            case 'd/m/Y':
                $arrayDate = explode('-', $datePreFilter);
                if (isset($arrayDate[0]) && isset($arrayDate[1]) && isset($arrayDate[2])
                    && (is_numeric($arrayDate[1]) && is_numeric($arrayDate[0]) && is_numeric($arrayDate[2])) 
                    && checkdate($arrayDate[1], $arrayDate[0], $arrayDate[2])) {
                    $isValidDate = true;
                }
                break;
            case 'Y-m-d':
                $arrayDate = explode('-', $datePreFilter);
                if (isset($arrayDate[0]) && isset($arrayDate[1]) && isset($arrayDate[2])
                    && (is_numeric($arrayDate[1]) && is_numeric($arrayDate[0]) && is_numeric($arrayDate[2])) 
                    && checkdate($arrayDate[1], $arrayDate[2], $arrayDate[1])) {
                    $isValidDate = true;
                }
                break;
            case 'd/m/Y H:i':
                $auxDate = explode(' ', $datePreFilter);
                if (isset($auxDate[0]) && isset($auxDate[1])) {
                    $arrayDate = explode('-',$auxDate[0]);
                    $hourMinute = $auxDate[1];
 
                    if ($this->isValidDate($auxDate[0]) &&
                            $this->isValidHour($hourMinute, 'H:i')) {
                         $isValidDate = true;
                    }
                }
                break;
            case 'd/m/Y H:i:s':
                $auxDate = explode(' ', $datePreFilter);
                if (isset($auxDate[0]) && isset($auxDate[1])) {
                    $arrayDate = explode('-',$auxDate[0]);
                    $hourMinute = $auxDate[1];
 
                    if ($this->isValidDate($auxDate[0]) && 
                        $this->isValidHour($hourMinute, 'H:i:s')) {
                         $isValidDate = true;
                    }
                }
                break;
            case 'Y-m-d H:i:s':
                $auxDate = explode(' ', $datePreFilter);
                if (isset($auxDate[0]) && isset($auxDate[1])) {
                    $arrayDate = explode('-',$auxDate[0]);
                    $hourMinute = $auxDate[1];
 
                    if ($this->isValidDate($auxDate[0], 'Y-m-d') && 
                        $this->isValidHour($hourMinute, 'H:i:s')) {
                         $isValidDate = true;
                    }
                }
                break;
            case 'Y-m-d H:i:s':
                $auxDate = explode(' ', $datePreFilter);
                if (isset($auxDate[0]) && isset($auxDate[1])) {
                    $arrayDate = explode('-',$auxDate[0]);
                    $hourMinute = $auxDate[1];
 
                    if ($this->isValidDate($auxDate[0], 'Y-m-d') && 
                        $this->isValidHour($hourMinute, 'H:i:s')) {
                         $isValidDate = true;
                    }
                }
                break;
        }
        return $isValidDate;
    }
 
    /**
     * Checks valid hour:minute or hour:minute:second
     * @param string $hour 
     * @param string $format [optional] H:i | H:i:s
     * @return boolean
     */
    public function isValidHour($hour, $format = 'H:i')
    {
        $isValidHour = false;
 
        switch ($format) {
            case 'H:i':
                if (preg_match("/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/", $hour)) {
                    $isValidHour = true;
                }
                break;
 
            case 'H:i:s':
                if (preg_match("/^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/", $hour)) {
                    $isValidHour = true;
                }
                break;
        }
 
        return $isValidHour;
    }
}
 
// Examples
$oDateHelper = new DateHelper();
 
$dateMySQL = '2014-10-30';
 
echo $oDateHelper->DateFormat($dateMySQL);
// 30 octubre 2014
 
echo $oDateHelper->DateFormat($dateMySQL,'large');
// jueves, 30 de octubre 2014
 
echo $oDateHelper->DateFormat($dateMySQL,'short'). "<br>";
// 30-10-2014
 
 
$spanishDate = '30/10/2014';
 
echo $oDateHelper->DateConvert($spanishDate);
// 2014-10-30 
 
echo $oDateHelper->DateConvert($spanishDate . ' 14:30', 'd/m/Y H:i');
// 2014-10-30 14:30:00
 
echo $oDateHelper->DateConvert($spanishDate . ' 14:30:25', 'd/m/Y H:i:s');
// 2014-10-30 14:30:25
 
 
$incorrectDate = '99/12/2014';
 
if (!$oDateHelper->isValidDate($incorrectDate)) {
    echo "Wrong date format";
}