注: 以下代码只在Chromium内核浏览器通过测试,其他浏览器还请自行测试。
Date 对象
创建一个 JavaScript
Date的实例,给对象呈现时间中的某个时刻。
Date对象基于 Unix Time Stamp ,即自1970年1月1日起经过的毫秒数。
创建一个 Date 对象
1// 获取一个当前时间的 Date 对象2var date = new Date();3// 从 1970年1月1日经过多少毫秒时间的 Date 对象4var date = new Date(1600000000000);5// 以一个日期字符串创建一个 Date 对象6var date = new Date("2020-2-2 22:22:22.2222");7var date = new Date('December 17, 1995 03:24:00');8var date = new Date('1995-12-17T03:24:00');9// 以年月日时分秒毫秒数字创建10var date = new Date(1995, 11, 17, 3, 24, 0, 100);常用操作
计算两个日期之间的相差(天/小时/分钟)
1var date1 = new Date("2020-2-1 20:00:00");2var date2 = new Date("2020-2-2 20:00:00");3var diffTime = parseInt(date2.getTime() / 1000) - (date1.getTime() / 1000);4var timeDay = parseInt(diffTime / 60 / 60 / 24); //相差天数5var timeHour = parseInt(diffTime / 60 / 60); //相差小时6var timeMinutes = parseInt(diffTime / 60); //相差分钟转换日期格式
- yyyy-MM-dd hh:mm 格式
1Date.prototype.format = function (fmt) {2 var o = {3 "M+": this.getMonth() + 1, //月份4 "d+": this.getDate(), //日5 "h+": this.getHours(), //小时6 "m+": this.getMinutes(), //分7 "s+": this.getSeconds(), //秒8 "q+": Math.floor((this.getMonth() + 3) / 3), //季度9 "S": this.getMilliseconds() //毫秒10 };11 if (/(y+)/.test(fmt)) {12 fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));13 }14 for (var k in o) {15 if (new RegExp("(" + k + ")").test(fmt)) {8 collapsed lines
16 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));17 }18 }19 return fmt;20}21
22var formatDate = new Date().format("yyyy-MM-dd hh:mm:ss");23console.log(formatDate);- yyyy/MM/dd 格式
1var date = new Date().toLocaleDateString();2console.log(date);- yyyy年MM月dd日 格式
其实这个格式把 ‘年月日’ 改成 ’-’ 就成了 yyyy-MM-dd hh:mm
格式
1var now = new Date(),2y = now.getFullYear(),3m = ("0" + (now.getMonth() + 1)).slice(-2),4d = ("0" + now.getDate()).slice(-2);5var date = y + "年" + m + "月" + d + "日" + now.toTimeString().substr(0, 8);6console.log(date);获取年、月、日、周、时、分、秒
1var date = new Date();2date.getFullYear(); // 年3date.getMonth(); // 月4date.getDate(); // 日5date.getHours(); // 时6date.getMinutes(); // 秒7
8// 注意 获取年的时候是 getFullYear() 而不是 getYear() 这是个小坑其他
详见 MDN Date