JS简单的日期格式化封装

日期格式化

第一个参数传入标准时间
第二个参数传入格式例如: 'yyyy-MM-DD' 'yyyy-MM-DD HH:mm:ss' 'HH:mm:ss' 'getDay'

function formatDate(date,format) {
    let myyear = date.getFullYear();
    let mymonth = date.getMonth() + 1;
    let myday = date.getDate();
    let myHours = date.getHours()
    let myMinutes = date.getMinutes()
    let mySeconds = date.getSeconds()

    if (mymonth < 10) {
        mymonth = "0" + mymonth;
    }
    if (myweekday < 10) {
        myweekday = "0" + myweekday;
    }
    if (myHours < 10) {
        myHours = "0" + myHours;
    }
    if (myMinutes < 10) {
        myMinutes = "0" + myMinutes;
    }
    if (mySeconds < 10) {
        mySeconds = "0" + mySeconds;
    }
    let dayNames = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
    let weekday = dayNames[date.getDay()]

    switch(format){
        case 'yyyy-MM-DD' : return (myyear + "-" + mymonth + "-" + myweekday);
        break;
        case 'yyyy-MM-DD HH:mm:ss' : return (myyear + "-" + mymonth + "-" + myweekday + " " + myHours + ":" + myMinutes + ":" + mySeconds);
        break;
        case 'HH:mm:ss' : return (myHours + ":" + myMinutes + ":" + mySeconds);
        break;
        case 'getDay' : return weekday;
        break
    }
}

export { formatDate }

组件中(例如):

import { formatDate } from '../config/DateFormatter'
formatDate(new Date() , 'HH:mm:ss')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容