时间格式转换

中国标准时间格式转换成常用时间格式

Mon Aug 29 2016 15:07:30 GMT+0800 (中国标准时间) --> 2016-08-29 15:07:30

方法一:

 1 //获取日期时间格式化字符串
 2 var getDateStringFromString = function(str,isAll){
 3     var date = new Date(str);
 4     var hour = date.getHours();
 5     hour = (hour < 10 ? "0" : "") + hour;
 6     var min  = date.getMinutes();
 7     min = (min < 10 ? "0" : "") + min;
 8     var sec  = date.getSeconds();
 9     sec = (sec < 10 ? "0" : "") + sec;
10     var year = date.getFullYear();
11     var month = date.getMonth() + 1;
12     month = (month < 10 ? "0" : "") + month;
13     var day  = date.getDate();
14     day = (day < 10 ? "0" : "") + day;
15     if(isAll){
16         return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
17     }else{
18         return year + "-" + month + "-" + day +" ";
19     }
20 };
21 
22 console.log(new Date()); //Mon Aug 29 2016 15:07:30 GMT+0800 (中国标准时间)
23 console.log(getDateStringFromString(new Date())); //2016-08-29
24 console.log(getDateStringFromString(new Date(),1)); //2016-08-29 15:07:30

 方法二:

 1 //author: meizz 
 2 Date.prototype.format = function(format){ 
 3   var o = { 
 4     "M+" : this.getMonth()+1, //month 
 5     "d+" : this.getDate(),    //day 
 6     "h+" : this.getHours(),   //hour 
 7     "m+" : this.getMinutes(), //minute 
 8     "s+" : this.getSeconds(), //second 
 9     "q+" : Math.floor((this.getMonth()+3)/3),  //quarter 
10     "S" : this.getMilliseconds() //millisecond 
11   } 
12   if(/(y+)/.test(format)) format=format.replace(RegExp.$1, 
13     (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
14   for(var k in o)if(new RegExp("("+ k +")").test(format)) 
15     format = format.replace(RegExp.$1, 
16       RegExp.$1.length==1 ? o[k] : 
17         ("00"+ o[k]).substr((""+ o[k]).length)); 
18   return format; 
19 } 
20 
21 var myFunction = function(){
22   var da= new Date();
23   var s=da.format("yyyy-MM-dd hh:mm:ss");
24   return s;
25 }
26 
27 console.log(new Date()); //Mon Aug 29 2016 15:17:51 GMT+0800 (中国标准时间)
28 console.log(myFunction(new Date())); // 2016-08-29 15:17:51

 方法三:

使用moment库,https://momentjs.com/

posted @ 2016-08-29 15:09  ximi007  阅读(396)  评论(0编辑  收藏  举报