封装日期函数


    <script>
        //封装日期
        //如果 年月日 时分秒只有一个数字则需要在前面增加一个0
        function twoNum(num) {
            return String(num).length > 1 ? num : "0" + num;
        }
        /* 
        @dateStr   传入的date值可以是str也可以是num //日期或者时间戳
        @format    期望获得的时间格式  
        return string 返回字符串
        */
        //创建一个dateFormat方法
        function dateFormat(dateStr, format) {
            //判断 传入的dateStr 是否为空值,如果为空值则读取当前时间,如果不是空值则为当前传入的值
            //Date 是一个构造函数  可以获取当前的时间作为一个对象
            var date = dateStr ? new Date(dateStr) : new Date();
            //获取年 月 日 时 分 秒
            var year = date.getFullYear();
            var month = date.getMonth();
            var day = date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var seconds = date.getSeconds();
            //创建一个对象 把years 赋值给字母YYYY  年月日时分秒依次赋值
            var date_map = {
                "YYYY": twoNum(year),
                "MM": twoNum(month + 1),
                "DD": twoNum(day),
                "hh": twoNum(hours),
                "mm": twoNum(minutes),
                "ss": twoNum(seconds),
                "YY": String(year).slice(2),
                "M": month,
                "D": day,
                "m": minutes,
                "h": hours,
                "s": seconds
            }
            //遍历data_map对象,读取里面的属性值,且把dateFormat中的属性替换成date_map
            Object.keys(date_map).forEach(function (key) {
                format = format.replace(key, date_map[key]);
            })
            //返回format
            return format;
        }
        var dt = dateFormat("1995/5/31 12:06:01", "YYYY-MM-DD hh-mm-ss");
        console.log(dt);
    </script>

2.网页显示日期

//网页显示时间
var box = document.querySelector(".box");
//写一个函数 获取时间
function showTime() {
    var date = new Date();
    box.innerText = date.getFullYear() + "年" + date.getMonth() + "月" + date.getDate() + "日" + date.getHours() + "时" + date.getMinutes() + "分" + date.getSeconds() + "秒";
}
//零秒的时候无显示 所以可以先手动调用
showTime();
//隔一秒获取一次
setInterval(showTime, 1000);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值