js对时间格式化

 

复制代码
/**
* @function
* @name us_date_format
* @param {string} _date - 不是时间字符串而时间对象,当值为字符串时需要对时间字符串进行处理new Date("2022-03-23 01:02:03")
* @param {string} fmt - 格式化样式  yyyy-MM-dd hh:mm:ss
* @desc 返回时间字符串
*/
function us_date_format(_date, fmt) {//console.log(_date);
    if (fmt == undefined) {
        fmt = "yyyy-MM-dd hh:mm:ss";
    }
    var o = {
        "M+": _date.getMonth() + 1, //月份
        "d+": _date.getDate(), //
        "h+": _date.getHours(), //小时
        "m+": _date.getMinutes(), //
        "s+": _date.getSeconds(), //
        "q+": Math.floor((_date.getMonth() + 3) / 3), //季度
        "S": _date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (_date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
                .length)));
        }
    }
    //console.log(fmt);
    return fmt;
}
复制代码

 测试:

var starttime="2023-03-23 02:03:04";
us_date_format(new Date(starttime), "yy年MM月dd日");  //23年03月23日
us_date_format(new Date(starttime), "yy-MM-dd");      //23-03-23
us_date_format(new Date(starttime), "yyyy-MM-dd");     //2023-03-23
us_date_format(new Date(starttime), "yyyy年-MM月-dd日");//2023年-03月-23日
us_date_format(new Date(starttime), "yyyy-MM-dd hh:mm:ss");//2023-03-23 02:03:04
us_date_format(new Date(starttime), "yyyy年MM月dd日 hh时mm分ss秒");//2023年03月23日 02时03分04秒 

 

posted @   じ逐梦  阅读(296)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
历史上的今天:
2022-03-23 .Net Core 运用ADO实现添加功能+验证邮箱是否存在+单个文件上传+手动(图片上传)、代码自动创建文件夹
点击右上角即可分享
微信分享提示