JavaScript 时间格式化 js时间转换
2019-04-01 11:21
239 查看
1. 第一种方式 - 自定义方法(推荐)
[code]/** * 第一种方式-自定义方法(推荐) */ function dateFtt(fmt, date) { if(!date) date = new Date(); if(!(date instanceof Date)) date = new Date(date); var o = { "M+" : date.getMonth()+1, //月份 "d+" : date.getDate(), //日 "h+" : date.getHours(), //小时 "m+" : date.getMinutes(), //分 "s+" : date.getSeconds(), //秒 "q+" : Math.floor((date.getMonth()+3)/3), //季度 "S" : date.getMilliseconds() //毫秒 }; if(/(y+)/.test(fmt)) fmt=fmt.replace(RegExp.$1, (date.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; } // 调用方法 alert(dateFtt("yyyy-MM-dd hh:mm:ss")); // 不传时间参数时为当前时间 alert(dateFtt("yyyy年MM月dd日", new Date())); alert(dateFtt("yyyy-MM-dd h:m:s", new Date())); // 获取当前时间(使用Date对象转换) alert(dateFtt("yyyy-MM-dd hh:mm:ss", 1554079891497)); // 使用时间戳转换
第二种方式 - 修改内置函数
[code]/** * 第二种方式-修改内置函数 */ Date.prototype.format = function (format) { var args = { "M+": this.getMonth() + 1, "d+": this.getDate(), "h+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "q+": Math.floor((this.getMonth() + 3) / 3), //quarter "S": this.getMilliseconds() }; if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var i in args) { var n = args[i]; if (new RegExp("(" + i + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length)); } return format; }; // 调用方法 alert(new Date().format("yyyy年MM月dd日")); alert(new Date().format("yyyy/MM/dd")); alert(new Date().format("yyyy-MM-dd hh:mm:ss")); alert(new Date(1554079891497).format("yyyy-MM-dd hh:mm:ss")); alert(new Date(new Date().getTime() + 2 * (24 * 60 * 60 * 1000)).format("yyyy-MM-dd")); // 加两天
相关文章推荐
- JS时间格式化,时间戳的转换
- 用JavaScript(js)对时间格式化
- js 时间戳转换成格式化日期 日期格式化
- JS 将 格式化的时间 转换成 时间戳
- javascript时间格式format函数,js日期格式化函数
- Javascript、js 时间日期时间戳转换
- JavaScript时间戳格式化转换
- 用JavaScript(js)对时间格式化
- JavaScript 格式化日期,转换时间日期格式
- 用JavaScript(js)对时间格式化
- javascript、 JS日期格式化转换方法
- 用JavaScript(js)对时间格式化
- 用JavaScript(js)对时间格式化
- js中已格式化时间的正则相互转换
- 用JavaScript(js)对时间格式化
- js 中时间戳转换格式化日期
- javascript中常见的函数封装 :判断是否是手机,判断是否是微信,获取url地址?后面的具体参数值,毫秒格式化时间,手机端px、rem尺寸转换等
- 用JavaScript(js)对时间格式化
- JS 时间格式化
- Js获取当前日期时间及格式化操作