js 中时间格式化的几种方法

1.项目中时间返回值,很过时候为毫秒值,我们需要转换成 能够看懂的时间的格式;

  例如: yyyy-MM-dd HH:mm:ss

 

2.处理方法(处理方法有多种,可以传值到前端处理,也可以后台可以好之后再传递到页面)

    方法一:实体类中添加时间转换注解(注意时区问题)

/**
  * 开始时间
  */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8") private Date startTime;

     

     方法二:js处理

data-options=
{ field : 'crtTime', title : '创建时间', width : 100, sortable :true, align : 'center', formatter : crtTimeFtt }
//渲染事件 formatter
function crtTimeFtt(val, row) { if (val != null) { var date = new Date(val); return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(); } }

 

   方法三:JS处理(创建公共类方法)

 1 /**************************************时间格式化处理************************************/
 2 function dateFtt(fmt,date) {   
 3   var o = {   
 4     "M+" : date.getMonth()+1,                 //月份   
 5     "d+" : date.getDate(),                    //
 6     "h+" : date.getHours(),                   //小时   
 7     "m+" : date.getMinutes(),                 //
 8     "s+" : date.getSeconds(),                 //
 9     "q+" : Math.floor((date.getMonth()+3)/3), //季度   
10     "S"  : date.getMilliseconds()             //毫秒   
11   };   
12   if(/(y+)/.test(fmt)) {
13     fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
14   }
15   for(var k in o) {  
16      if(new RegExp("("+ k +")").test(fmt))   
17      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
18   }
19   return fmt;   
20 }
21 dateFtt("yyyy-MM-dd hh:mm:ss",new Date());

 

     相应JS文件里面的引用

//创建时间格式化显示
function crtTimeFtt(value,row,index){
    var crtTime = new Date(value);
    return top.dateFtt("yyyy-MM-dd hh:mm:ss",crtTime);//直接调用公共JS里面的时间类处理的办法     
}

   方法四:js处理

 

关于Date对象(原文:https://blog.csdn.net/baidu_37107022/article/details/78450368 )

创建一个日期对象: 
var objDate=new Date([arguments list]); 

参数形式有以下5种: 
1)new Date("month dd,yyyy hh:mm:ss"); 
2)new Date("month dd,yyyy"); 
3)new Date(yyyy,mth,dd,hh,mm,ss); 
4)new Date(yyyy,mth,dd); 
5)new Date(ms); 
注意:
    在程序中我使用的第三种初始化方法,总是显示格式化的参数不正确,
    仔细看了一下一定要是整型的才可以,我传递的是字符串 

需要注意最后一种形式,参数表示的是需要创建的时间和 GMT时间1970年1月1日之间相差的毫秒数。各种函数的含义如下: 

month:用英文 表示月份名称,从January到December 
mth:用整数表示月份,从(1月)到11(12月) 
dd:表示一个 月中的第几天,从1到31 
yyyy:四位数表示的年份 
hh:小时数,从0(午夜)到23(晚11点) 
mm: 分钟数,从0到59的整数 
ss:秒数,从0到59的整数 
ms:毫秒数,为大于等于0的整数 

如: 
new Date("January 12,2006 22:19:35"); 
new Date("January 12,2006"); 
new Date(2006,0,12,22,19,35); 
new Date(2006,0,12);
new Date(1137075575000); 
new Date()方法不传参数时,默认获取的是当前日期。

 

posted @ 2019-04-10 12:34  絵飛ヾ的魚  阅读(2038)  评论(0编辑  收藏  举报