1 某天前后几天日期
function addDayToDate(date, num) {
//num 为正数表示num天后,负数表示num天前
const d = new Date(date);
const day = d.getDate();
d.setDate(day + num);
return d.toISOString().split("T")[0];
}
2 某天是当年的第几天
function daysOfYear(dateStr) {
const d = new Date(dateStr);
const date = new Date(d.getFullYear(), 0, 0);
const num = Math.floor((d - date) / 1000 / 3600 / 24);
return num;
}
3 获取当前时间 年月日时分秒星期
/** * * @param {number|string|object} time * @param {string} cFormat */
function formatTime(time, cFormat) {
// 不传默认今天
let date = time;
const dayStr = ["日", "一", "二", "三", "四", "五", "六"];
const format = cFormat || "y-m-d h:i:s";
if (!time) {
date = new Date();
}
if (typeof date == "string") {
// 2020-12-24
date = date.replace(/-/gm, "/");
date = new Date(date);
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
};
const timeStr = format.replace(/([ymdhisa])+/g, (result, key) => {
let value = formatObj[key];
if (key == "a") {
return "星期" + dayStr[value];
}
return value.toString().padStart(2, "0");
});
return timeStr;
}