这是我参与11月更文挑战的第8天,活动详情查看:2021最后一次更文挑战
1. 将日期格式化成字符串
由于东西方的日期显示格式不同,所以要显示其他格式的日期就需要对日期进行日期格式化操作,如:
MM-YYYY-DD h:m:sYYYY/MM/DD h-m-sYYYY:MM:DD h:m:s
// 日期格式化成字符串
function dateFormat() {
Date.prototype.format = function(f) {
var date = { //获取对象中的日期
"Y": this.getFullYear(), // 获取年
"M": (this.getMonth() + 1), // 获取月
"D": this.getDate(), // 获取日
"h": this.getHours(), // 获取时
"m": this.getMinutes(), // 获取分
"s": this.getSeconds() // 获取秒
},
d = "", // 初始化接受日期变量的对象
r = false, // 判断是否存在待替换的字符
reg = null, // 正则
_d = ""; // 日期
for (d in date) { // 过滤日期标识符
reg = new RegExp("[" + d + "]{1,}", "g"); // 判断是否有待格式化的字符
r = reg.test(f);
if (r) { // 验证是否存在
_d = date[d];
f = f.replace(reg, _d < 10 ? ("0" + _d) : _d);
}
}
return f;
}
}
// 调用
var d = new Date();
dateFormat();
document.getElementById("formatTime1").innerHTML = "格式化日期1:" + d.format("YYYY-MM-DD h:m:s");
document.getElementById("formatTime2").innerHTML = "格式化日期2:" + d.format("YYYY/MM/DD h-m-s");
document.getElementById("formatTime3").innerHTML = "格式化日期3:" + d.format("YYYY:MM:DD h:m:s");
- 在 Date 原型链 prototype 上扩展;
- 过滤日期标识符,检查传入的字符 f 中是否有符合待替换的日期格式;
2. 获取指定日期是第几周
function getMonthDays(Y, M) {
return new Date(Y, M, 0).getDate();
}
function getHowManyWeeks(Y, M, D) {
var totalDays = 0, // 总天数
i = 1; // 默认开始为第一个月
for (; i < M; i++) {
totalDays += getMonthDays(Y, M);
}
totalDays += D;
return Math.ceil(totalDays / 7); // 除以7,向上取整,计算第几周
}
document.getElementById("getHowManyWeeks").innerHTML = "第" + getHowManyWeeks("2021", "2", "20") + "周";
- 以月份 M 为最大的循环范围,计算月份 M 之前有多少天;
- 加上 D 天,即为所有累加的天数;
- 除以7,向上取整;
3. 倒计时
经常需要计算距离某个节日的天数,如电商狂欢节
function getCountDown(Y, M, D, h, m, s) {
Y = Y || 0;
M = M || 0;
D = D || 0;
h = h || 0;
m = m || 0;
s = s || 0;
var date = new Date(Y, M-1, D, h, m, s),
times = date.getTime() - new Date().getTime(); // 转换为时间戳,方便计算差值
return Math.ceil(times / (1000 * 60 * 60 * 24)); // 返回天数
}
// 到指定日期时间的倒计时
document.getElementById("getCountDown").innerHTML = "2022 年 2 月 14 日距离现在:" + getCountDown("2022", "2", "14") + "天";
// 节日倒计时
document.getElementById("LabourDay").innerHTML = "劳动节距离现在:" + getCountDown("2022", "5", "1") + "天";
document.getElementById("NationalDay").innerHTML = "国庆节距离现在:" + getCountDown("2022", "10", "1") + "天";
- 将待比较的两个日期转换为相同的时间戳;
- 比较计算后的时间戳,除以1000,就可以计算出相差多少秒;