码迷,mamicode.com
首页 > 其他好文 > 详细

日期,字符串,毫秒值的相互转换

时间:2019-09-20 15:19:22      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:var   length   OLE   ret   replace   转换   pre   seconds   fun   

<script>
        
        Date.prototype.format = function(fmt) { 
             var o = { 
                "M+" : this.getMonth()+1,                 //月份 
                "d+" : this.getDate(),                    //
                "h+" : this.getHours(),                   //小时 
                "m+" : this.getMinutes(),                 //
                "s+" : this.getSeconds(),                 //
                "q+" : Math.floor((this.getMonth()+3)/3), //季度 
                "S"  : this.getMilliseconds()             //毫秒 
            }; 
            if(/(y+)/.test(fmt)) {
                    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
            }
             for(var k in o) {
                if(new RegExp("("+ k +")").test(fmt)){
                     fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
                 }
             }
            return fmt; 
        }
        //将日期对象格式化为字符串
        console.log(new Date().format("yyyy-MM-dd hh:mm:ss"));
        
        //将字符串转化为日期对象
        //2015-12-15 20:11:11
        //2018.08.16 12:15:11
        //2018/08/16 12:15:11  可以接受的格式有很多
        var str = "2018/08/16 12:15:11";
        console.log(new Date(str));
        
        //日期转化为毫秒值
        console.log(new Date().getTime());
        //毫秒值转化为日期
        console.log(new Date(1568962985134));

    </script>

 

日期,字符串,毫秒值的相互转换

标签:var   length   OLE   ret   replace   转换   pre   seconds   fun   

原文地址:https://www.cnblogs.com/mayiaction/p/11557327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!