概述
Date 对象用于处理日期和时间。
// 创建 Date 对象的语法
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
注意:Date 对象会自动把当前日期和时间保存为其初始值。
Date的属性
constructor
返回对创建此对象的 Date 函数的引用。
prototype
向Date对象添加属性和方法, 例如 Date.prototype.format = function(fmt)
。
Date的日期格式
js的标准日期格式
new Date(); // Fri Apr 09 2021 20:52:04 GMT+0800 (中国标准时间)
js的UTC日期格式
UTC(Universal Time Coordinated)等同于 GMT(格林威治时间)
new Date().toUTCString(); // "Fri, 09 Apr 2021 12:56:10 GMT"
js的 ISO日期格式
完整的格式 日期和时间通过大写字母 T 来分隔
new Date().toJSON(); // "2021-04-09T13:04:56.375Z"
Date转换
时间戳->日期对象
var date = new Date(1617894984466);
日期对象->时间戳
var time = new Date().getTime();
var time = new Date().valueOf();
var time = Date.parse(new Date())
日期对象->斜杆形式的字符串
// 根据本地时间格式,把 Date 对象的日期部分转换为字符串。
date.toLocaleDateString();
// 根据本地时间格式,把 Date 对象转换为字符串。
date.toLocaleString();
Date的方法
var date = new Date();
date.getFullYear();// 获取完整的年份
date.getMonth(); // 获取月份 使用需要加 1
date.getDate(); // 获取天数
Date格式化
简单的格式化方法
function dateFormat (val) {
if (val != null) {
var date = new Date(val);
return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
}
}
定义公用的日期格式化方法
Date.prototype.format = function(fmt){
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)){
fmt=fmt.replace(RegExp.$1, (this.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;
}