Helper函数库:日期格式化
15 浏览2025年02月17日作者:Auntie13

一个相对完整的日期格式化函数

/**
 * 格式化日期为指定的字符串格式
 * @param {Date} date - 要格式化的 Date 对象
 * @param {string} format - 日期格式字符串,例如 'yyyy-MM-dd EEEE HH:mm:ss 第ww周'
 * @returns {string} 格式化后的日期字符串
 */
function formatDate(date, format) {
    const pad = (num) => String(num).padStart(2, '0');

    const year = date.getFullYear();
    const month = pad(date.getMonth() + 1); // 月份从0开始,需要加1
    const day = pad(date.getDate());
    const weekOfYear = getWeekOfYear(date);
    const dayOfWeek = date.getDay(); // 0(星期日)到6(星期六)
    const hours = pad(date.getHours());
    const minutes = pad(date.getMinutes());
    const seconds = pad(date.getSeconds());

    // 定义星期几的中文表示
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];

    const replacements = {
        'yyyy': year,
        'yy': year.toString().slice(-2),
        'MM': month,
        'M': month.slice(-1),
        'dd': day,
        'd': day.slice(-1),
        'ww': pad(weekOfYear),
        'w': weekOfYear,
        'EEEE': weekdays[dayOfWeek],
        'EEE': weekdays[dayOfWeek].slice(0, 3),
        'HH': hours,
        'H': hours.slice(-1),
        'mm': minutes,
        'm': minutes.slice(-1),
        'ss': seconds,
        's': seconds.slice(-1)
    };

    return format.replace(/yyyy|yy|MM|M|dd|d|ww|w|EEEE|EEE|HH|H|mm|m|ss|s/g, match => replacements[match]);
}

/**
 * 获取指定日期在一年中的第几周
 * @param {Date} date 
 * @returns {number}
 */
function getWeekOfYear(date) {
    const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
    const dayNum = d.getUTCDay() || 7;
    d.setUTCDate(d.getUTCDate() + 4 - dayNum);
    const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
    return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
}

// 示例用法:
const date = new Date(2023, 11, 12, 15, 30, 45); // 2023年12月12日 15:30:45
const formattedDate = formatDate(date, 'yyyy-MM-dd EEEE HH:mm:ss 第ww周');
console.log(formattedDate); // 输出示例: "2023-12-12 星期二 15:30:45 第49周"
最后一次编辑于 2025 年 02 月 17 日
共 0 条评论

相关文章

专题推荐

热门文章

热门问答