Skip to content

Instantly share code, notes, and snippets.

@nmvuong92
Last active January 18, 2019 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmvuong92/224b861f1e146b2de36377f403435ab5 to your computer and use it in GitHub Desktop.
Save nmvuong92/224b861f1e146b2de36377f403435ab5 to your computer and use it in GitHub Desktop.
php xử lý datetime timestamp

Datetime Class

Tạo biến dữ liệu thời gian theo chuẩn UTC/GMT/Z bằng Datetime Class

$date1 = new DateTime('now', new DateTimeZone('utc')); //DateTime tạo đối tượng Datetime múi giờ utc chuẩn london có giá trị là hiện tại
$date2 = new DateTime('2019-01-17', new DateTimeZone('utc')); //DateTime  tạo đối tượng Datetime múi giờ utc chuẩn london có giá trị 17/01/2019 00:00:00
var_dump($date1,$date2);

kết quả

D:\www\vsmarty\crfs\demo.php:24:
object(DateTime)[1]
  public 'date' => string '2019-01-18 06:17:23.841066' (length=26)
  public 'timezone_type' => int 2
  public 'timezone' => string 'UTC' (length=3)
D:\www\vsmarty\crfs\demo.php:24:
object(DateTime)[2]
  public 'date' => string '2019-01-17 00:00:00.000000' (length=26)
  public 'timezone_type' => int 2
  public 'timezone' => string 'UTC' (length=3)

diff => trả về DateInterval => dùng để so sánh khoảng chênh lệch giữa 2 giá trị thời gian

 $diff = $date1->diff($date2);
 var_dump($diff); //DateInterval

kết quả:

D:\www\vsmarty\crfs\demo.php:26:
object(DateInterval)[3]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 1
  public 'h' => int 6
  public 'i' => int 17
  public 's' => int 23
  public 'f' => float 0.841066
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 1
  public 'days' => int 1
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0

phép tính thời gian

year, month, day, hour, minute, second, milisecond, millisecond

cộng

ví dụ tạo một biến thời gian sau đó cộng thêm giá trị 1 ngày

	$now = new DateTime('now', new DateTimeZone('utc')); //DateTime hiện tại
    var_dump($now);
    $now->modify("+1 day"); //hiện tại cộng thêm 1 ngày
    var_dump($now);

trừ

	$now = new DateTime('now', new DateTimeZone('utc')); //DateTime hiện tại
    var_dump($now);
 	$now->modify("-1 day"); //hiện tại trừ đi 1 ngày
    var_dump($now);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment