<?php
/**
 * Created by PhpStorm.
 * User: rocho
 * Date: 2016. 09. 08.
 * Time: 7:01
 */

namespace common\components;

use yii\i18n\Formatter;

class DateUtil
{
    /**
     * Get UTC today @00:00:00 .
     * Helper method to generate date for mysql
     *
     * @return \DateTime
     */
    public static function todayStart( ){
        $d2 = new \DateTime();
        $d2->setTimezone( new \DateTimeZone( "UTC" ) );
        $d2->setTime(0, 0, 0);
        return $d2;
    }

    /**
     * Get UTC t @00:00:00 .
     * Helper method to generate date for mysql
     *
     * @return \DateTime
     */
    public static function tomorrowStart( ){
        $d2 = new \DateTime();
        $d2->add(new \DateInterval('P1D'));
        $d2->setTimezone( new \DateTimeZone( "UTC" ) );
        $d2->setTime(0, 0, 0);
        return $d2;
    }



    public static function addMonth($timestamp, $monthCount = 1)
    {

        if ($timestamp instanceof \DateTime) {
            $d1 = $timestamp;
        } else {

            $d1 = new \DateTime();

            if (isset($timestamp)) {
                $d1->setTimestamp($timestamp);
            }
        }

        $monthToAdd = $monthCount;


        $year = $d1->format('Y');
        $month = $d1->format('n');
        $day = $d1->format('d');

        $year += floor($monthToAdd / 12);
        $monthToAdd = $monthToAdd % 12;
        $month += $monthToAdd;
        if ($month > 12) {
            $year++;
            $month = $month % 12;
            if ($month === 0)
                $month = 12;
        }

        if (!checkdate($month, $day, $year)) {
            $d2 = \DateTime::createFromFormat('Y-n-j', $year . '-' . $month . '-1');
            $d2->modify('last day of');
        } else {
            $d2 = \DateTime::createFromFormat('Y-n-d', $year . '-' . $month . '-' . $day);
        }
        $d2->setTime(0, 0, 0);


        return $d2;
    }


    public static function formatUtc($dateTimeObject)
    {
        $formatter = new Formatter;
        $formatter->datetimeFormat = 'php:Y-m-d H:i:s';
        $formatter->timeZone = 'UTC';
        return $formatter->asDatetime($dateTimeObject);
    }

    public static function formatDateUtc($dateTimeObject)
    {
        $formatter = new Formatter;
        $formatter->datetimeFormat = 'php:Y-m-d';
        $formatter->timeZone = 'UTC';
        return $formatter->asDatetime($dateTimeObject);
    }

    public static function parseDate($dateString){

        $date =  \DateTime::createFromFormat("Y.m.d",  $dateString, new \DateTimeZone( 'UTC'));
        $date->setTime(0, 0, 0);
        return $date;
    }

}