前端计算未来时间

前言

        前端开发人员在遇到和时间控件相关的需求时,就有可能涉及到对时间选择的限制,比如只限定当前时间之后的七天时间可选。除此之外,比如限定只展示当前时间至未来30天的这个时间段的数据等,这些需求就涉及到计算未来时间了。

        本文以一个计算未来30天时间的例子来说明前端是怎么来计算未来时间,代码如下:

// let currentTime = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + ' ' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds();

// 或者用下面两行代码计算当前时间
let getDate = new Date();
let currentTime = getDate.getFullYear() + '-' + (getDate.getMonth() + 1) + '-' + getDate.getDate() + ' ' + getDate.getHours() + ':' + getDate.getMinutes() + ':' + getDate.getSeconds();

// 计算30天的时间戳(计算任意时间段的时间戳同理)
let timer = 30 * 24 * 60 * 60 * 1000;
let allTimer = new Date(currentTime).getTime() + timer;
console.log(new Date(allTimer).toLocaleString()); // 2022/1/8 下午9:37:48  原生toLocaleString方法不符合我们想要的格式

// 重写toLocaleString方法来达到我们想要的格式
Date.prototype.toLocaleString = function() {
    function addZero(num) {
        return num < 10 ? "0" + num : num;
    };
    // this 指向(就是) new Date()
    // 按自定义拼接格式返回
    return this.getFullYear() + "/" + addZero(this.getMonth() + 1) + "/" + addZero(this.getDate()) + " " + addZero(this.getHours()) + ":" + addZero(this.getMinutes());
};

console.log(new Date(allTimer).toLocaleString()); // 2022/01/08 21:41

        如果读者对作者所用方法有所建议,或者自己有更高明的方法,欢迎评论区留言讨论,如果觉得不错,请点赞推荐给更多的人看到哦,转载请注明出处,感谢~

       作者公众号:程序的艺术,欢迎关注一起探寻更多的程序艺术

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值