js获取当前时间并设定返回格式、时分秒转换为秒

1、时间格式化

复制代码
/**
 * 返回当前时间字符串
 * @param {any} fmt 格式化格式  yyyy-MM-dd hh:mm:ss
 */
function us_date_getnow(fmt) {
    var mydate = new Date();
    return this.us_date_format(mydate, fmt);
}

/**
* @function
* @name us_date_format
* @param {string} _date - 时间  new Date("2023-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;
}
复制代码

测试:

us_date_getnow("yyyy-MM-dd ");
us_date_getnow("yyyy-MM-dd hh:mm:ss");
us_date_getnow("yyyy年MM月dd日 hh时mm分ss秒");

 2、当前时间时分秒转换为秒

复制代码
//#region 2.获取时间秒
/**
 * 获取时间秒
 * @param {any} date 时间字符串 09:31:44
 */
function gettimesecond(date) {
    var darr = date.split(':');
    return parseInt(darr[0]) * 3600 + parseInt(darr[1]) * 60 + parseInt(darr[2]);
}
//#endregion
复制代码

 

posted @   じ逐梦  阅读(896)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-03-23 .Net Core 运用ADO实现添加功能+验证邮箱是否存在+单个文件上传+手动(图片上传)、代码自动创建文件夹
点击右上角即可分享
微信分享提示