'admin-21.06.21:优化时间工具类,感谢群友@我觉得还行'

This commit is contained in:
lyt 2021-06-21 15:49:16 +08:00
parent 2462f110ef
commit 79f08c362c

View File

@ -5,11 +5,13 @@
* @description format `YYYY-mm、YYYY-mm-dd` * @description format `YYYY-mm、YYYY-mm-dd`
* @description format "YYYY-mm-dd HH:MM:SS QQQQ" * @description format "YYYY-mm-dd HH:MM:SS QQQQ"
* @description format "YYYY-mm-dd HH:MM:SS WWW" * @description format "YYYY-mm-dd HH:MM:SS WWW"
* @description format + "YYYY-mm-dd HH:MM:SS WWW QQQQ" * @description format "YYYY-mm-dd HH:MM:SS ZZZ"
* @description format + + "YYYY-mm-dd HH:MM:SS WWW QQQQ ZZZ"
* @returns * @returns
*/ */
export function formatDate(date: Date, format: string): string { export function formatDate(date: Date, format: string): string {
let we = date.getDay(); // 星期 let we = date.getDay(); // 星期
let z = getWeek(date); // 周
let qut = Math.floor((date.getMonth() + 3) / 3).toString(); // 季度 let qut = Math.floor((date.getMonth() + 3) / 3).toString(); // 季度
const opt: { [key: string]: string } = { const opt: { [key: string]: string } = {
'Y+': date.getFullYear().toString(), // 年 'Y+': date.getFullYear().toString(), // 年
@ -40,6 +42,7 @@ export function formatDate(date: Date, format: string): string {
if (/(W+)/.test(format)) if (/(W+)/.test(format))
format = format.replace(RegExp.$1, RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? '星期' + week[we] : '周' + week[we]) : week[we]); format = format.replace(RegExp.$1, RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? '星期' + week[we] : '周' + week[we]) : week[we]);
if (/(Q+)/.test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 4 ? '第' + quarter[qut] + '季度' : quarter[qut]); if (/(Q+)/.test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 4 ? '第' + quarter[qut] + '季度' : quarter[qut]);
if (/(Z+)/.test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 3 ? '第' + z + '周' : z + '');
for (let k in opt) { for (let k in opt) {
let r = new RegExp('(' + k + ')').exec(format); let r = new RegExp('(' + k + ')').exec(format);
// 若输入的长度不为1则前面补零 // 若输入的长度不为1则前面补零
@ -48,6 +51,27 @@ export function formatDate(date: Date, format: string): string {
return format; return format;
} }
/**
*
* @param dateTime
* @returns
*/
export function getWeek(dateTime: Date): number {
let temptTime = new Date(dateTime.getTime());
// 周几
let weekday = temptTime.getDay() || 7;
// 周1+5天=周六
temptTime.setDate(temptTime.getDate() - weekday + 1 + 5);
let firstDay = new Date(temptTime.getFullYear(), 0, 1);
let dayOfWeek = firstDay.getDay();
let spendDay = 1;
if (dayOfWeek != 0) spendDay = 7 - dayOfWeek + 1;
firstDay = new Date(temptTime.getFullYear(), 0, 1 + spendDay);
let d = Math.ceil((temptTime.valueOf() - firstDay.valueOf()) / 86400000);
let result = Math.ceil(d / 7);
return result;
}
/** /**
* `几秒前``几分钟前``几小时前``几天前` * `几秒前``几分钟前``几小时前``几天前`
* @param param new Date() * @param param new Date()