js获取n分钟(或n小时或n个月)后(或前)的时间(日期)

  标题有点绕,其实意思就是根据系统当前时间,获取n分钟或n小时或n个月后的时间。

  例如:当前时间下,获取10分钟后的时间。

1
2
3
4
5
6
7
8
9
10
11
var date=new Date();     //1. js获取当前时间
var min=date.getMinutes();  //2. 获取当前分钟
date.setMinutes(min+10);  //3. 设置当前时间+10分钟:把当前分钟数+10后的值重新设置为date对象的分钟数
var y = date.getFullYear();
var m = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1);
var d = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate();
var h = date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours()
var f = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes()
var s = date.getSeconds() < 10 ? ('0' + date.getseconds()) : date.getSeconds()
var formatdate = y+'-'+m+'-'+d + " " + h + ":" + f + ":" + s;
console.log(formatdate) // 获取10分钟后的时间,格式为yyyy-mm-dd h:f:s

  同理,设置30分钟,60分钟或1个小时,5个小时,可以将小时转换为分钟,然后获取当前分钟再加上需要设置的时间即可。

 

  获取1个月后的日期:

1
2
3
4
5
6
7
8
9
10
var date=new Date();
date.setMonth(date.getMonth()+1);
var y = date.getFullYear();
var m = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1);
var d = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate();
var h = date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours()
var f = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes()
var s = date.getSeconds() < 10 ? ('0' + date.getseconds()) : date.getSeconds()
var formatwdate = y+'-'+m+'-'+d + " " + h + ":" + f + ":" + s;
console.log('formatwdate', formatwdate)

  同理获取n个月后或n个月前的日期都是如此

posted @   江峰★  阅读(14771)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示