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

AI 概述
把 JavaScript 里的时间值转换为指定格式的时间文本; JavaScript 代码 /** * 时间服务 */ let $TimeService = function () { let $this = this; /** * 输出格式化的文本 * @param {Date} date 时间 * @param {number} format 天数 */ this.ToStringFormat= function (da...

把 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');

以上关于JavaScript 时间值转换为指定格式的时间文本的文章就介绍到这了,更多相关内容请搜索码云笔记以前的文章或继续浏览下面的相关文章,希望大家以后多多支持码云笔记。

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 admin@mybj123.com 进行投诉反馈,一经查实,立即处理!
重要:如软件存在付费、会员、充值等,均属软件开发者或所属公司行为,与本站无关,网友需自行判断
码云笔记 » JavaScript 时间值转换为指定格式的时间文本

发表回复