Chuyển đổi định dạng ngày tháng năm
Định dạng ngày giờ trong PHP, chuyển ngày hiện tại hiển thị với nhiều định dạng. Có 2 format ngày tháng năm chuẩn là:“m-d-Y”: month,day,year
“Y-m-d”: year, month,day
Ví dụ chuyển từ Y-m-d sang d-m-Y
1
2
| $originalDate = "2010-03-21";$newDate = date("d-m-Y", strtotime($originalDate)); |
Bạn có thể thay ký tự – thành /
1
2
| //even accept format of date: d/m/Yecho date('d/m/Y',strtotime('13-10-2013')); #return 13/10/2013 |
Phép toán với thời gian
Cộng +30 ngày tính từ thời điểm hiện tại.
1
2
| //+ 30 days tính từ ngày hôm naystrtotime( '+30 days' ); |
1
| strtotime('+1 day',strtotime('2013-10-30')); //+ tính từ ngày nào đó. |
strtotime như thế này.
1
2
3
4
| <?phpecho date( "Y-m-d", strtotime( "2009-01-31 +1 month" ) ); // PHP: 2009-03-03echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP: 2009-03-31?> |
So sánh sự chệnh lệch giữa 2 ngày
1
2
3
4
5
6
7
8
9
10
| <?php/** * calculate date different * */$t1=new DateTime('2013-10-29 17:0:0');$t2=new DateTime('2013-10-31 14:1:50');$s=$t1->diff($t2);print_r($s); //DateInterval Object ( [y] => 0 [m] => 0 [d] => 1 [h] => 21 [i] => 1 [s] => 50 [invert] => 0 [days] => 1 )#1 ngày =24h, chuyển thành hours?> |
SQL
– Trong lệnh sql có hàm DATE_ADD cho phép bạn thực hiện phép toán cộng ngày với ngày lưu trong database.
1
| SELECT DATE_ADD( '2009-01-31', INTERVAL 1 MONTH ); -- MySQL: 2009-02-28 |
Hàm
date('Y-m-d') tương ứng với DATE_FORMAT(NOW(),"%Y-%m-%d") trong sql.Cho nên khi insert vào table thì dùng trực tiếp hàm sql nhé
Cộng gộp 2 thời gian
Bạn muốn tạo một hàm để cộng 2 thời gian mà không cần sử dụng hàmexplode.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| <?php function add2times($hour_one,$hour_two){ //$hour_one = "01:20:20"; //$hour_two = "05:50:20"; $h = strtotime($hour_one); $h2 = strtotime($hour_two); $minute = date("i", $h2); $second = date("s", $h2); $hour = date("H", $h2); echo "<br>"; $convert = strtotime("+$minute minutes", $h); $convert = strtotime("+$second seconds", $convert); $convert = strtotime("+$hour hours", $convert); $new_time = date('H:i:s', $convert); echo $new_time;}?> |
– Lấy ngày cuối cùng của tháng.
1
2
3
4
5
6
7
8
9
10
11
12
| //last day of monthfunction lastday($month = '', $year = '') { if (empty($month)) { $month = date('m'); } if (empty($year)) { $year = date('Y'); } $result = strtotime("{$year}-{$month}-01"); $result = strtotime('-1 second', strtotime('+1 month', $result)); return date('Y-m-d', $result);} |
1
2
3
4
5
6
7
8
9
10
11
12
| //first day of monthfunction firstDay($month = '', $year = ''){ if (empty($month)) { $month = date('m'); } if (empty($year)) { $year = date('Y'); } $result = strtotime("{$year}-{$month}-01"); return date('Y-m-d', $result);} link website: http://www.hoangweb.com/php/xu-ly-ngay-gio-trong-php |
Không có nhận xét nào:
Đăng nhận xét