web建站教程
  1. 首页
  2. vuejs
  3. js
  4. 地图大全
  5. AIGC工具
  6. 前端知识
  7. 百度echarts
  8. 更多
    php入门
    nodejs
    mockjs
    reactjs
    mysql
    wordpress
    织梦cms
    帝国cms
    git教程
    IT知识
    模板大全
    休息站
    手机应用

js获取两个时间之间的所有日期、月份、年份

1219 ℃

用JS实现获取2个时间点之间的日期、月份、年份(包括区间自身),代码如下:

1、获取日期

function getTimeTwo(start, end) {
  let diffdate = new Array();
  let arr = []
  let i = 0;
  while (start <= end) {
    diffdate[i] = start;
    let stime_ts = new Date(start).getTime();
    let next_date = stime_ts + (24 * 60 * 60 * 1000);
    let next_dates_y = new Date(next_date).getFullYear() + '-';
    let next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) + '-' : (new Date(next_date).getMonth() + 1) + '-';
    let next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(next_date).getDate();
    start = next_dates_y + next_dates_m + next_dates_d;
    i++;
  }
  return diffdate;
}
console.log(getTimeTwo('2022-01-12','2022-01-31'))

2、获取月份

function getMonthBetween(start, end) {
  let result = [];
  let min = new Date(start);
  let max = new Date(end);
  let curr = min;
  while (curr <= max) {
    let month = new Date(curr).getMonth() + 1;
    let t = ""
    if (month < 10) {
      t = '0' + month
    } else t = month
    let str = curr.getFullYear() + "-" + (t);
    let s = curr.getFullYear() + "-0";
    if (str == s) {
      str = curr.getFullYear() + "-12";
    }
    result.push(str);
    curr.setMonth(month);
  }
  return result;
}
console.log(getMonthBetween('2022-01','2023-12'))

3、获取年份

function getYearBetween(start, end){
  let result = [];
  let min = new Date(start).getFullYear();
  let max = new Date(end).getFullYear();
  while (min <= max) {
    result.push(min);
    min = (Number(min) + 1)
  }
  return result;
}
console.log(getYearBetween('2021-01-01','2022-01-01'))

jQuery如何获取下一个子标签

es6语法中如何利用next()实现手动遍历对象

js关于Date对象的所有方法介绍

var、let、const的区别(什么时候调用)

php如何利用函数修改时差

标签: date let new next start

上面是“js获取两个时间之间的所有日期、月份、年份”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。

当前网址:https://ipkd.cn/webs_2009.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

当前位置: 网站首页 > js
本文共计1387个字,预计阅读时长10分钟
Trae:新一代免费的AI编程工具

在线育儿补贴计算器

快来看看你到底可以领到多少补贴!

生活小工具

收录了万年历、老黄历、八字智能排盘等100+款小工具!生活小工具
上一篇: 推荐一款免费在线图片处理工具——佐糖图片平台
下一篇: 推荐一款优设网免费可商用字体——优设标题黑体
x 打工人ai神器