给网站首页添加系统时间

<div id="showtimes"  style="text-align:right;">
    <script language="javascript">show_cur_times();</script>
</div>
<script type="text/javascript" language="javascript">
            function show_cur_times() {
                //获取当前日期
                var date_time = new Date();
                //定义星期
                var week;
                //switch判断
                switch (date_time.getDay()) {
                    case 1: week = "星期一"; break;
                    case 2: week = "星期二"; break;
                    case 3: week = "星期三"; break;
                    case 4: week = "星期四"; break;
                    case 5: week = "星期五"; break;
                    case 6: week = "星期六"; break;
                    default: week = "星期天"; break;
                }

                //
                var year = date_time.getFullYear();
                //判断小于10,前面补0
                if (year < 10) {
                    year = "0" + year;
                }

                //
                var month = date_time.getMonth() + 1;
                //判断小于10,前面补0
                if (month < 10) {
                    month = "0" + month;
                }

                //
                var day = date_time.getDate();
                //判断小于10,前面补0
                if (day < 10) {
                    day = "0" + day;
                }

                //
                var hours = date_time.getHours();
                //判断小于10,前面补0
                if (hours < 10) {
                    hours = "0" + hours;
                }

                //
                var minutes = date_time.getMinutes();
                //判断小于10,前面补0
                if (minutes < 10) {
                    minutes = "0" + minutes;
                }

                //
                var seconds = date_time.getSeconds();
                //判断小于10,前面补0
                if (seconds < 10) {
                    seconds = "0" + seconds;
                }

                //拼接年月日时分秒
                var date_str = year + "年" + month + "月" + day + "日 " + hours + ":" + minutes + ":" + seconds + " " + week;

                //显示在id为showtimes的容器里
                document.getElementById("showtimes").innerHTML = date_str;
            }

            //设置1秒调用一次show_cur_times函数
            setInterval("show_cur_times()", 1000);
        </script>

总结:

1.这里是对javascript Date对象的应用

2.主要使用Date对象的getDay(),getFullYear(),getMonth(),getDate()等方法进行拼接从而显示出想要的时间格式

3.javascript Date对象使用详解:http://www.w3school.com.cn/jsref/jsref_obj_date.asp

 

posted @ 2017-04-19 21:09  单纯的桃子  阅读(368)  评论(0编辑  收藏  举报