【新手案例】JavaScript用Date方法封装一个获取string格式时间函数的方式

 分享一些上课时的笔记给大家

运行效果:

实现代码: 

<script type="text/javascript">
    //日期Date对象方法,必须先实例化再使用,实例化可以传参数 参数为时间戳 或 文本时间
    //实例化Date方法给now对象
    // var now = new Date('2015-06-05');
    // //获取时间戳
    // console.log(now.getTime());
    // console.log(now.valueOf());
    // var nowTime;
    // nowTime = now.getFullYear() + '-' + now.getMonth() + '-' + now.getDate();
    // console.log(nowTime);

    //封装时间格式的string输出函数
    function GetTime(datestr) {
        //三元判断:变量 = 表达式 ? 真 输出的值 : 假 输出的值;
        datestr = datestr == undefined ? Date.now() : datestr;
        var now = new Date(datestr);

        var year = now.getFullYear();
        var month = now.getMonth();
        month += 1;
        var date = now.getDate();
        var hours = now.getHours();
        var min = now.getMinutes();
        var sec = now.getSeconds();

        month = month < 10 ? '0' + month : month;
        date = date < 10 ? '0' + date : date;
        min = min < 10 ? '0' + min : min;
        sec = sec < 10 ? '0' + sec : sec;
        var nowTime = year + '-' + month + '-' + date + ' ' + hours + ':' + min + ':' + sec + '';
        return nowTime;
    }


    console.log(GetTime());
    console.log(GetTime('2015-5-5 12:12:12'));
</script>

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值