• NodeJs获取两个日期间的所有日期


     1 const moment = require( 'moment' );
     2 
     3 const begin_date = '2017-12-12',
     4     end_date = '2018-01-19',
     5     arr = getAllDays( begin_date, end_date );
     6 
     7 console.log( 'arr: ', arr );
     8 
     9 function getAllDays( begin_date, end_date ) {
    10     const errArr = [],
    11         resultArr = [],
    12         dateReg = /^[2]d{3}-[01]d-[0123]d$/;
    13 
    14     if ( typeof begin_date !== 'string' || begin_date === '' || !dateReg.test( begin_date ) ) {
    15         return errArr;
    16     }
    17 
    18     if ( typeof end_date !== 'string' || end_date === '' || !dateReg.test( end_date ) ) {
    19         return errArr;
    20     }
    21 
    22     try {
    23         const beginTimestamp = Date.parse( new Date( begin_date ) ),
    24             endTimestamp = Date.parse( new Date( end_date ) );
    25 
    26         // 开始日期小于结束日期
    27         if ( beginTimestamp > endTimestamp ) {
    28             return errArr;
    29         }
    30 
    31         // 开始日期等于结束日期
    32         if ( beginTimestamp === endTimestamp ) {
    33             resultArr.push( begin_date );
    34             return resultArr;
    35         }
    36 
    37         let tempTimestamp = beginTimestamp,
    38             tempDate = begin_date;
    39 
    40 
    41         // 新增日期是否和结束日期相等, 相等跳出循环
    42         while ( tempTimestamp !== endTimestamp ) {
    43             resultArr.push( tempDate );
    44 
    45             // 增加一天
    46             tempDate = moment( tempTimestamp )
    47                 .add( 1, 'd' )
    48                 .format( 'YYYY-MM-DD' );
    49 
    50             // 将增加时间变为时间戳
    51             tempTimestamp = Date.parse( new Date( tempDate ) );
    52         }
    53 
    54         // 将最后一天放入数组
    55         resultArr.push( end_date );
    56         return resultArr;
    57 
    58     } catch ( err ) {
    59         return errArr;
    60     }
    61 }
  • 相关阅读:
    雨天拍照技巧
    was8.5和aop的问题:JVMVRFY013 违反类装入约束o
    Docker Swarm
    Docker compose
    docker 网络
    dockerFile
    docker容器数据卷
    docker容器数据卷
    dokcer镜像详解
    Portainer可视化面板安装
  • 原文地址:https://www.cnblogs.com/maduar/p/8060472.html
Copyright © 2020-2023  润新知