您的位置:首页 > Web前端 > JavaScript

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")); // 加两天

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: