프로그래밍/PHP

php 시간 표현 예시 - dateTime 사용 예시

kugancity 2020. 12. 31. 23:31
반응형



- 현재 시간 구하기 (YYYY-mm-dd) format




        $current_date = new DateTime();

        $current_date->format('Y-m-d');

  



- 현재 요일 구하기




function get_day_of_week($sql_date)

{

        $updated_date = new DateTime($sql_dat);

        $day_of_week = $updated_date->format('D');

        return $day_of_week;

}







- 두 시간 표현 간 시간 차이 구하기 

참고: http://haruair.com/blog/1871, http://php.net/manual/kr/datetime.diff.php





public DateInterval DateTime::diff ( DateTimeInterface $datetime2 [, bool $absolute = false ] )





       $date_db= new DateTime();

        $date_news=new DateTime("2014-01-28");

        $diff=$date_db->diff($date_news);

        print "\ndiff days".$diff->days; // 522



        if($date_news <= $date_db)

        {

            echo "\nnews data is older than or same as db\n";

            break;

        }

        else

        {

            echo "\nnews data is newer than db\n";


- 두 개의 시간 비교하기 

최신일 수록 값이 크기 때문에 오늘과 미래를 비교하면 비교식에서 미래가  오늘보다 더 크다 
 

<?php
$date1 = new DateTime("now"); or $date1= new DateTime();

$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);
?>

위 예제의 출력:

bool(false)
bool(true)
bool(false)





- 특정 날짜의 하루 전 날 구하기 

참고: http://php.net/manual/en/datetime.modify.php



<?php
$date = new DateTime('2006-12-12');
$date->modify('-1 day');
echo $date->format('Y-m-d');
?>








728x90
반응형