const DATE_FORMAT = "YYYY-MM-DD hh:mm:ss";
export function taskDateFormat(targetDate) {
if (targetDate) {
const currentYear = new Date().getFullYear();
const targetDateYear = new Date(targetDate).getFullYear();
const format = currentYear !== targetDateYear ? "YYYY.MM.DD" : "MM.DD";
return formatDate(targetDate, format);
}
return "";
}
/**
* formatDate
* @param {string | Date} date
* @param {string} fmt "YYYY-MM-DD hh:mm:ss";
* @return {string}
*/
export function formatDate(date, fmt = DATE_FORMAT) {
if (typeof date === "string") date = new Date(date);
if (!(date instanceof Date)) return "";
const yearMatch = fmt.match(/(Y+)/);
const yearFormat = yearMatch && yearMatch[1];
if (yearFormat) {
fmt = fmt.replace(
yearFormat,
`${date.getFullYear()}`.substring(4 - yearFormat.length, 4)
);
}
let o = {
"M+": date.getMonth() + 1,
"D+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
};
for (let k in o) {
const reg = new RegExp(`(${k})`);
if (reg.test(fmt)) {
let str = `${o[k]}`;
const format = fmt.match(reg)[1];
fmt = fmt.replace(format, format.length === 1 ? str : padLeftZero(str));
}
}
return fmt;
}
function padLeftZero(str) {
return ("00" + str).substring(str.length);
}