Cách để get time hiện tại trong PHP chúng ta có thể sử dụng hàm date với bất kì phiên bản PHP nào , hoặc tốt hơn có thể dùng datetime class với phiên bản từ 5.2
Ví dụ sử dụng hàm date:
Để trả về thời gian định dang Y-m-d H:i:s chúng ta sử dụng code sau:
1
2
3
|
<?php
echo date(‘Y-m-d H:i:s’);
?>
|
Ví dụ sử dụng Datetime class:
Để trả về thời gian định dang Y-m-d H:i:s chúng ta sử dụng code sau:
1
2
3
4
|
<?php
$dt = new DateTime();
echo $dt->format(‘Y-m-d H:i:s’);
?>
|
Tìm hiểu thêm thông tin về thời gian:
Ví dụ trên sẽ trả về giá trị thời gian hiện của server với timezone được định nghĩa trong file php.ini , ví dụ:
1
2
3
4
|
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Europe/Athens
|
Ngoài ra chúng ta còn có thể chỉ định timezone theo UTC. UTC là viết tắt của standard international time. Sử dụng php với datetime class sẽ dễ dàng tính toán được thời gian của người sử dụng đang ở timezone UTC nào.
Định nghĩa timezone trên server theo UTC và định dạng ngày tháng hiển thị:
1
2
3
4
5
|
/* server timezone */
define(‘CONST_SERVER_TIMEZONE’, ‘UTC’);
/* server dateformat */
define(‘CONST_SERVER_DATEFORMAT’, ‘YmdHis’);
|
Trong trường hợp này, bạn có thể sử dụng funtion sau để lấy dữ liệu thời gian:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<?php
/**
* Converts current time for given timezone (considering DST)
* to 14-digit UTC timestamp (YYYYMMDDHHMMSS)
*
* DateTime requires PHP >= 5.2
*
* @param $str_user_timezone
* @param string $str_server_timezone
* @param string $str_server_dateformat
* @return string
*/
function now($str_user_timezone,
$str_server_timezone = CONST_SERVER_TIMEZONE,
$str_server_dateformat = CONST_SERVER_DATEFORMAT) {
// set timezone to user timezone
date_default_timezone_set($str_user_timezone);
$date = new DateTime(‘now’);
$date->setTimezone(new DateTimeZone($str_server_timezone));
$str_server_now = $date->format($str_server_dateformat);
// return timezone to server default
date_default_timezone_set($str_server_timezone);
return $str_server_now;
}
?>
|
Hi vọng nó hữu ích với bạn. Có câu hỏi vui lòng comment để Vietpro giải đáp cho các bạn nhé.
Xem thêm khóa học lập trình web PHP !