Date的常用方法

198 阅读1分钟
  1. Date的构造函数形式
    1. new Date(): 返回当前日期的Date对象;
        // Sun Sep 26 2021 14:38:16 GMT+0800 (中国标准时间)
    
    2. new Date(1000): 返回距19701108:00:00后的毫秒对应日期;
        // Thu Jan 01 1970 08:00:01 GMT+0800 (中国标准时间)
    
    3. new Date('2016-01-01 12:00:00'): 返回指定时间的日期;'-' 可以换成 '/'
        // new Date('2016/01/01 12:00:00')
        // new Date(2016,4,5,17,55,55)
  1. Date.parse(new Date()): 返回时间戳;
  2. new Date().getTime(): 返回时间戳;
  3. new Date().getFullYear(): 返回年份;
  4. new Date().getMonth(): 返回0-11月份;
  5. new Date().getDate(): 返回1~31日;
  6. new Date().getDay(): 返回一周中的某一天(0-6);
  7. new Date().getHours(): 返回小时数0-23;
  8. new Date().getMinutes(): 返回分钟数0-59;
  9. new Date().getSeconds(): 返回秒钟数0-59;

需要注意的时区问题:

image.png

new Date('2023-01-09') 会有时区问题,默认到08:00:00,所以做时间限制的需要注意

另推荐一个非常好的时间处理器库: Moment.js

官网:momentjs.cn/docs/

里面有时间的加减等各种常用的处理方式;