[JavaScript][js]时间值转换为指定格式的时间文本

2 篇文章 0 订阅
2 篇文章 0 订阅

开发作者:Jackie Law
开发时间:2021-07-20
开发语言:Javascript
浏 览 器:Microsoft Edge(版本 92.0.902.62 )

需求

1.把JavaScript里的时间值转换为指定格式的时间文本;

一.JavaScript代码

/**
 * 时间服务
 */
let $TimeService = function () {
    let $this = this;

    /**
     * 输出格式化的文本
     * @param {Date} date 时间
     * @param {number} format 天数
     */
    this.ToStringFormat= function (date, format) {
        let _date = date;

        let _result = format;
        //const _Weeks = ['日', '一', '二', '三', '四', '五', '六'];

        _result = _result.replace(/yyyy|YYYY/, _date.getFullYear());
        _result = _result.replace(/yy|YY/, (_date.getYear() % 100).toString().padStart(2, '0'));

        let _month = (_date.getMonth() + 1).toString();
        _result = _result.replace(/MM/, _month.padStart(2, '0'));
        _result = _result.replace(/M/g, _month);

        //_result = _result.replace(/w|W/g, _Weeks[_date.getDay()]);

        _result = _result.replace(/dd|DD/, _date.getDate().toString().padStart(2, '0'));
        _result = _result.replace(/d|D/g, _date.getDate());

        _result = _result.replace(/hh|HH/, _date.getHours().toString().padStart(2, '0'));
        _result = _result.replace(/h|H/g, _date.getHours());
        _result = _result.replace(/mm/, _date.getMinutes().toString().padStart(2, '0'));
        _result = _result.replace(/m/g, _date.getMinutes());

        _result = _result.replace(/ss|SS/, _date.getSeconds().toString().padStart(2, '0'));
        _result = _result.replace(/s|S/g, _date.getSeconds());

        _result = _result.replace(/fff|fff/, _date.getMilliseconds().toString().padEnd(3, '0').substring(0, 3));
        _result = _result.replace(/ff|ff/, _date.getMilliseconds().toString().padEnd(2, '0').substring(0, 2));
        _result = _result.replace(/f|f/g, _date.getMilliseconds().toString().padEnd(1, '0').substring(0, 1));

        return _result;
    };

    /**
     * 时间增加天数
     * @param {Date} date 时间
     * @param {number} days 天数
     */
    this.AddDays: function (date, days) {
        if (!date) { return date; }
        if (!days) { return date; }
        return new Date(date.setDate(date.getDate() + days));
    };

};

二.使用方式

1.在A.html页面引用该Js文件;
2.js代码

$TimeService.ToStringFormat(new Date(),'yyyy-MM-dd');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值