Jun 14, 2013

Kiểu DateTime trong PHP

Một số thủ thuật để xử lý DateTime trong PHP: lấy ngày tháng hiện tại, so sánh ngày, tính thời gian chênh lệch giữa 2 ngày.


- Lấy ngày hiện tại:

$now=  new DateTime(date('Y-m-d H:i:s');
echo $now->format('Y-m-d H:i:s');
- Get yesterday at 23:59:59:
public function getYesterday() {
        $_yesterday_date_str = date('Y-m-d', strtotime('-1 days'));
        $_24h_yesterdate = new DateTime($_yesterday_date_str);
        $_24h_yesterdate->setTime(23, 59, 59);
        return $_24h_yesterdate;
    }// return Datetime Oject


- Tính thời gian khác nhau giữa 2 ngày:

We has two dates are start_date and end_date which query from db, format: Y-m-d H:i:s, ex: 2013-06-15 20:30:40

$a is array which $a['start_date']='2013-06-15 20:30:40' and $a['end_date']='2013-07-15 20:30:40'

$start_date = new DateTime($a['start_date']);
            $end_date = new DateTime($a['end_date']);


$seconds += 
strtotime(date_format($end_date, 'Y-m-d H:i:s')) - strtotime(date_format($start_date , 'Y-m-d H:i:s'));

$days = floor($seconds / 86400);
        $hours = floor(($seconds - ($days * 86400)) / 3600);
        $minutes = floor(($seconds - ($days * 86400) - ($hours * 3600)) / 60);
        $seconds = floor(($seconds - ($days * 86400) - ($hours * 3600) - ($minutes * 60)));
        $ff = $days * 24;
        $time = $ff + $hours . " hours" . $minutes . " mins ".$seconds.'s' ;

echo $time;

- So sánh ngày (Yêu cầu php 5.2.2+)
<?php
$date1 
= new DateTime("now");

$date2 = new DateTime("tomorrow");var_dump($date1 == $date2);
var_dump($date1 $date2);var_dump($date1 $date2); 
?>
Kết quả:
bool(false)
bool(true)
bool(false)
 
 

No comments:

Post a Comment