Kỹ thuật xử lý thời gian trong PHP thực tế

http://hocthietkeweb.net.vn/wp-content/uploads/2015/07/php-developer.jpg

Hôm nay mình sẽ trình bày bài viết Kỹ thuật xử lý thời gian trong PHP thực tế, đối với bài viết này mình sẽ đưa ra các tình huống thao tác với thời gian trong thực tế mà chúng ta thường gặp, cũng như cách giải quyết cho từng tình huống này. Các tình huống mà mình trình bày sẽ bao gồm các nội dung sau:
·         Định dạng lại cách hiển thị ngày khi sử dụng Datepicker
·         Hiển thị thời gian theo định dạng: 01:57 PM Thứ 3, ngày 18/06/2013
·         Kiểm tra năm nhuận
·         Tìm số ngày trong tháng của một năm nào đó
·         Xác định khoảng thời gian giữa hai ngày (như ở ứng dụng Facebook )
·         So sánh hai ngày bất kỳ
·         Xây dựng hàm để thực hiện thao tác cộng, trừ thời gian
Bài tập 1: Định dạng lại cách hiển thị ngày khi sử dụng Datepicker
·         Tìm hiểu hàm strtotime
1
2
3
4
5
6
7
$timeStampe = strtotime("now");
$timeStampe = strtotime("18 June 2013");
$timeStampe = strtotime("next Monday");
$timeStampe = strtotime("15-Mar-2013");
$timeStampe = strtotime("15/06/2013");

echo date('d/m/Y', $timeStampe);
·          Tìm hiểu hàm date_parse_from_format
1
2
3
4
5
$date = date_parse_from_format('d/m/Y H:i:s', '15/06/2013 13:20:35') ;

$timeStampe            = mktime($date['hour'], $date['minute'], $date['second'], $date['month'], $date['day'], $date['year']);

echo date('H:i:s d/m/Y', $timeStampe);
·          Định dạng lại cách hiển thị ngày khi sử dụng Datepicker
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <title>jQuery UI Datepicker - Default functionality</title>
                <link rel="stylesheet" href="../css/jquery-ui.css" />
                <link rel="stylesheet" href="../css/style.css" />
                <script src="../js/jquery-1.9.1.js"></script>
                <script src="../js/jquery-ui.js"></script>
                <script type="text/javascript">
                                $(function() {
                                    $( "#datepicker" ).datepicker({
                                                dateFormat: "dd/mm/yy",
                                                defaultDate: "+3d",
                                                changeYear: true,
                                                changeMonth: true,
                                                yearRange: "2000:2015"
                                    });
                                });
                  </script>
</head>
<body>
                <div class="content">
                                <h1>Exercise 01</h1>
                                <?php
                                                $date = (isset ( $_POST ["datepicker"] )) ? $_POST ["datepicker"] : "";
                                ?>
               
                                <form action="#" method="post" name="mainForm" id="mainForm">
                                                <div class="row">
                                                                <span>Date: </span>
                                                                <input readonly="readonly" type="text" id="datepicker" name="datepicker" value="<?php echo $date;?>" />
                                                </div>
                                                <div class="row">
                                                                <input type="submit" value="Submit" />
                                                </div>
                                </form>
                                <div class="result">
                                <?php
                                                echo "Input: " . $date . "<br />";
                                                $date = date_parse_from_format('d/m/Y', $date) ;
                                               
                                                $timeStampe            = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);
                                               
                                                echo "Output: " . date("d-m-Y", $timeStampe);
                                ?>
                                </div>
                </div>
</body>
</html>

Bài tập 2: Hiển thị thời gian theo định dạng: 01:57 PM Thứ 3, ngày 18/06/2013
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
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <title>Làm vic vi thi gian</title>
                <link rel="stylesheet" href="../css/style.css" />


</head>
<body>
                <div class="content">
                                <h1>Làm vic vi thi gian</h1>
                                <?php
                                                // 03:09 PM Thứ 3, ngày 18/06/2013
                                                // 03:09 PM Tue, 18/06/2013                 
                               
                                                $result = date('h:i A D, \n\g\à\y d/m/Y', time());
                                               
                                                $arrEn     = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
                                                $arrVi      = array('Thứ 2', 'Thứ 3', 'Thứ 4', 'Thứ 5', 'Thứ 6', 'Thứ 7', 'Chủ nhật');
                                               
                                                $result     = str_replace($arrEn, $arrVi, $result);
                                                //$result   = str_replace(',', ', ngày', $result);
                                               
                                                echo $result;
                                ?>
                </div>
</body>
</html>

Bài tập 3: Kiểm tra năm nhuận
·         Cách 01 Tự xây dựng hàm kiểm tra năm nhuận
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
30
31
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <title>Làm vic vi thi gian</title>
                <link rel="stylesheet" href="../css/style.css" />


</head>
<body>
                <div class="content">
                                <h1>Làm vic vi thi gian</h1>
                                <?php
                                                // Leap year: n chia het cho 4 và (n chia het 400 hoặc n khong chia het cho 100)
                                                // n % 400 == 0 || (n % 4 == 0 && n % 100 != 0)                 
                                                function testLeapYear($year){
                                                                $flag = false;
                                                                if( ($year % 400 == 0) || ($year % 4 == 0 && $year % 100 != 0) ) $flag = true;
                                                                return $flag;
                                                }
                                               
                                                $year = 2012;
                                                if(testLeapYear($year)){
                                                                echo "Năm nhuận";
                                                }else {
                                                                echo "Không là Năm nhuận";
                                                }
                                ?>
                </div>
</body>
</html>

·         Cách 02: Sử dụng hàm checkdate của PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <title>Làm vic vi thi gian</title>
                <link rel="stylesheet" href="../css/style.css" />


</head>
<body>
                <div class="content">
                                <h1>Làm vic vi thi gian</h1>
                                <?php
                                                $year = 2013;
                                                if(checkdate(2, 29, $year)){
                                                                echo "Năm nhuận";
                                                }else {
                                                                echo "Không là Năm nhuận";
                                                }
                                ?>
                </div>
</body>
</html>

Bài tập 4: Tìm số ngày trong tháng của một năm nào đó
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <title>Làm vic vi thi gian</title>
                <link rel="stylesheet" href="../css/style.css" />


</head>
<body>
                <div class="content">
                                <h1>Làm vic vi thi gian</h1>
                                <?php
                                                $month    = 2;
                                                $year       = 2013;
                                               
                                                $timeStampe = mktime(0, 0, 0, $month, 1, $year);
                                                echo $totalDays       = date('t', $timeStampe);
                                ?>
                </div>
</body>
</html>

Bài tập 5: Xác định khoảng thời gian giữa hai ngày (như ở ứng dụng Facebook )
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
30
31
32
33
34
35
36
37
38
39
40
// timePost so sánh timeCurrent
$timePost = '18/06/2013 09:20:23';
$timeReply              = '29/06/2013 10:20:38';

$datePost = date_parse_from_format('d/m/Y H:i:s', $timePost);
$dateReply              = date_parse_from_format('d/m/Y H:i:s', $timeReply);

$tsPost                    = mktime($datePost['hour'], $datePost['minute'], $datePost['second'], $datePost['month'], $datePost['day'], $datePost['year']);
$tsReply  = mktime($dateReply['hour'], $dateReply['minute'], $dateReply['second'], $dateReply['month'], $dateReply['day'], $dateReply['year']);

$distance = $tsReply - $tsPost;

// 23 seconds ago
// 23 minutues ago
// 2 hours ago
// Yesterday at 09:20:23
// 18/06/2013 at 09:20:23


switch ($distance){
                case ($distance < 60):
                                $result = ($distance == 1) ? $distance . ' second ago' : $distance . ' seconds ago';
                                break;
                case ($distance >= 60 && $distance < 3600):
                                $minute   = round($distance/60);
                                $result = ($minute == 1) ? $minute . ' minute ago' : $minute . ' minutes ago';
                                break;
                case ($distance >= 3600 && $distance < 86400):
                                $hour       = round($distance/3600);
                                $result = ($hour == 1) ? $hour . ' hour ago' : $hour . ' hours ago';
                                break;
                case (round($distance/86400)==1):
                                $result = 'Yesterday at ' . date('H:i:s', $tsReply);
                                break;
                default:
                                $result = date('d/m/Y \a\t H:i:s', $tsReply);
                                break;
}

echo $result;

Bài tập 6: So sánh hai ngày bất kỳ
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <title>jQuery UI Datepicker - Default functionality</title>
                <link rel="stylesheet" href="../css/jquery-ui.css" />
                <link rel="stylesheet" href="../css/style.css" />
                <script src="../js/jquery-1.9.1.js"></script>
                <script src="../js/jquery-ui.js"></script>
                <script type="text/javascript">
                                $(function() {
                                    $( "#date-start" ).datepicker({
                                                dateFormat: "dd/mm/yy",
                                                defaultDate: "+3d",
                                                changeYear: true,
                                                changeMonth: true,
                                                yearRange: "2000:2015"
                                    });
                                    $( "#date-end" ).datepicker({
                                                dateFormat: "dd/mm/yy",
                                                defaultDate: "+3d",
                                                changeYear: true,
                                                changeMonth: true,
                                                yearRange: "2000:2015"
                                    });
                                });
                  </script>
</head>
<body>
                <div class="content">
                                <h1>Exercise 06</h1>
                                <?php
                                                $dateStart = (isset ( $_POST ["date-start"] )) ? $_POST ["date-start"] : "";
                                                $dateEnd = (isset ( $_POST ["date-end"] )) ? $_POST ["date-end"] : "";
                                ?>
               
                                <form action="#" method="post" name="mainForm" id="mainForm">
                                                <div class="row">
                                                                <span>Start: </span>
                                                                <input readonly="readonly" type="text" id="date-start" name="date-start" value="<?php echo $dateStart;?>" />
                                                </div>
                                                <div class="row">
                                                                <span>End: </span>
                                                                <input readonly="readonly" type="text" id="date-end" name="date-end" value="<?php echo $dateEnd;?>" />
                                                </div>
                                                <div class="row">
                                                                <input type="submit" value="Submit" />
                                                </div>
                                </form>
                                <div class="result">
                                <?php
                                               
                                               
                                                function compareTwoDay($dateStart, $dateEnd ){
                                                                // Start
                                                                $arrDateStart           = date_parse_from_format('d/m/Y', $dateStart) ;
                                                                $tsStart                    = mktime(0, 0, 0, $arrDateStart['month'], $arrDateStart['day'], $arrDateStart['year']);
                                                                               
                                                                // End
                                                                $arrDateEnd = date_parse_from_format('d/m/Y', $dateEnd) ;
                                                                $tsEnd                     = mktime(0, 0, 0, $arrDateEnd['month'], $arrDateEnd['day'], $arrDateEnd['year']);
                                                               
                                                                // 0, 1, -1
                                                                $result = 0;
                                                                if($tsEnd > $tsStart) {
                                                                                $result = 1;
                                                                }else if ($tsEnd < $tsStart){
                                                                                $result = -1;
                                                                }
                                                                return $result;
                                                }
                                               
                                                if(compareTwoDay($dateStart, $dateEnd)==1){
                                                                echo "End > Start";
                                                }else if(compareTwoDay($dateStart, $dateEnd)==-1){
                                                                echo "Start > End";
                                                }else {
                                                                echo "End = Start";
                                                }
                                ?>
                                </div>
                </div>
</body>
</html>

Bài tập 7: Xây dựng hàm để thực hiện thao tác cộng, trừ thời gian
·         Xây dựng tập tin functions.php định nghĩa các hàm
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
30
31
32
33
34
function createSelectbox($arrData, $name, $keySelected){
                $strDays = "";
                if(!empty($arrData)) {
                                $strDays = '<select name="'.$name.'">';
                                for($i = 0; $i < count($arrData); $i++){
                                                if($keySelected == $i){
                                                                $strDays .= '<option value="'.$i.'" selected="true">'.$arrData[$i].'</option>';
                                                }else{
                                                                $strDays .= '<option value="'.$i.'">'.$arrData[$i].'</option>';
                                                }
                                                               
                                }
                                $strDays .= '</select>';
                }
                return $strDays;
}
               
function addTime($date, $format, $type, $value){
                $arrDate  = date_parse_from_format($format, $date);
                $type = strtolower($type);
                switch ($type){
                                case 'day':
                                                $ts = mktime(0, 0, 0, $arrDate['month'],  $arrDate['day'] + $value,  $arrDate['year']);
                                                break;
                                case 'month':
                                                $ts = mktime(0, 0, 0, $arrDate['month'] + $value,  $arrDate['day'],  $arrDate['year']);
                                                break;
                                case 'year':
                                                $ts = mktime(0, 0, 0, $arrDate['month'],  $arrDate['day'],  $arrDate['year'] + $value);
                                                break;
                }
                $result = date($format, $ts);
                return $result;
}
·          Xây dựng tập tin index.php xử lý yêu cầu của bài tập
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <title>jQuery UI Datepicker - Default functionality</title>
                <link rel="stylesheet" href="../css/jquery-ui.css" />
                <link rel="stylesheet" href="../css/style.css" />
                <script src="../js/jquery-1.9.1.js"></script>
                <script src="../js/jquery-ui.js"></script>
                <script type="text/javascript">
                                $(function() {
                                    $( "#date" ).datepicker({
                                                dateFormat: "dd/mm/yy",
                                                defaultDate: "+3d",
                                                changeYear: true,
                                                changeMonth: true,
                                                yearRange: "2000:2015"
                                    });
                                  
                                });
                  </script>
</head>
<body>
                <div class="content">
                                <h1>Exercise 07</h1>
                                <?php
                                                require_once 'function.php';
                                                $arrType = array('-- Select type --','Day', 'Month', 'Year');
                                               
                                               
                                                // Lay gia tri nguoi dung nhap vao
                                                $date        = (isset ( $_POST ["date"] )) ? $_POST ["date"] : "";
                                                $type       = (isset ( $_POST ["select-type"] )) ? $_POST ["select-type"] : "";
                                                $value      = (isset ( $_POST ["value"] )) ? $_POST ["value"] : "";
                                               
                                                $strTypes = createSelectbox($arrType, 'select-type', $type);
                                               
                                               
                                ?>
                                <form action="#" method="post" name="mainForm" id="mainForm">
                                                <div class="row">
                                                                <span>Date: </span>
                                                                <input readonly="readonly" type="text" id="date" name="date" value="<?php echo $date;?>" />
                                                </div>
                                                <div class="row">
                                                                <span>Type</span>
                                                                <?php echo $strTypes;?>
                                                </div>
                                                <div class="row">
                                                                <span>Value</span>
                                                                <input type="text" id="value" name="value" value="<?php echo $value;?>" />
                                                </div>
                                                <div class="row">
                                                                <input type="submit" value="Submit" />
                                                </div>
                                </form>
                                <div class="result">
                                <?php
                                                echo $result = addTime($date, 'd/m/Y', $arrType[$type], $value);
                                ?>
                                </div>
                </div>
</body>
</html>

Kết thúc bài viết Kỹ thuật xử lý thời gian trong PHP thực tế mình đã giới thiệu cho các bạn khá nhiều các tình huống thao tác với thời gian trong thực tế. Nhìn lại các bài viết trước thì chúng ta đã tìm hiểu các vấn đề và các hàm để thao tác với array, string, number và date. Đây là 4 kiểu dữ liệu chúng ta rất thường xuyên làm việc với chúng trong lập trình PHP.

Comments

Popular Posts