zoukankan      html  css  js  c++  java
  • 时间格式转换

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

    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/

  • 相关阅读:
    hihoCoder #1077 RMQ问题再临-线段树
    ms sql 获取字符串首字母
    如何设置gen_server在退出时执行相关操作
    C++拾遗
    [置顶] Linux下文件和目录权限说明
    Android百度地图之显示地图
    USACO March. 2012
    JNI之HelloWorld
    复习C语言系列二:动态调用函数指针数组
    HDU2527:Safe Or Unsafe(哈弗曼树)
  • 原文地址:https://www.cnblogs.com/suiyueshentou/p/5818067.html
Copyright © 2011-2022 走看看