JavaScript—獲取本地時間以12小時制顯示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>獲取時間</title>
    <script type="text/javascript">
        function shijian() {
            var today = new Date();
            var hh = today.getHours();
            var mm = today.getMinutes();
            var ss = today.getSeconds();
            var day = today.getDay();
            var date = today.getDate();
            var year = today.getFullYear();
            var month = today.getMonth() + 1;

            /*聲明一個變量來接收轉換成字符串*/

            var dayday;

            /*用switch完成轉換操做*/
            switch (day) {
                case 1:
                    dayday = "一";
                    break;
                case 2:
                    dayday = "二";
                    break;
                case 3:
                    dayday = "三";
                    break;
                case 4:
                    dayday = "四";
                    break;
                case 5:
                    dayday = "五";
                    break;
                case 6:
                    dayday = "六";
                    break;
                case 7:
                    dayday = "日";
                    break;
            }

            /*聲明AM和PM分別表明上午和下午,由於時間設置爲12小時制,從用戶角度出發,提供便利*/

            var apm = "PM";
            var abm = "AM";

            /*從系統獲取的時間爲24小時制,咱們減去12就能夠轉換成12小時制*/

            if (hh > 12) {
                var num = hh - 12;
                document.getElementById("abc").innerHTML = "如今的系統時間:" + "<br/><br/>" + year + "年" + month + "月" + date + "日"
                    + num + "時" + mm + "分" + ss + "秒" + "&nbsp;" + "星期" + dayday + "&nbsp;" + "&nbsp;" + apm + "<br/><br/>" + "下午好!歡迎來到TB128!";
            } else {
                document.getElementById("abc").innerHTML = "如今的系統時間:" + "<br/><br/>" + year + "年" + month + "月" + date + "日"
                    + hh + "時" + mm + "分" + ss + "秒" + "&nbsp;" + "星期" + dayday + "&nbsp;" + "&nbsp;" + abm + "<br/><br/>" + "下午好!歡迎來到TB128!";
            }
        }

        /*每1000毫秒(1秒)執行一次shijian()方法*/
        
        setInterval("shijian()", 1000)
    </script>
</head>
<body>
<div id="abc">
    <input type="button" value="查看系統時間" onclick="shijian()">
</div>
</body>
</html>
相關文章
相關標籤/搜索