1

整理 js 日期对象的详细功能,使用 js 日期对象获取具体日期、昨天、今天、明天、每月...

 1 year ago
source link: https://www.cnblogs.com/jiangweiping/p/16950035.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

整理 js 日期对象的详细功能,使用 js 日期对象获取具体日期、昨天、今天、明天、每月天数、时间戳等,以及常用的日期时间处理方法

在 javascript 中内置了一个 Date 对象,可用于实现一些日期和时间的操作。

本文整理 js 日期对象的详细功能,使用 js 日期对象获取具体日期、昨天、今天、明天、每月天数、时间戳等,以及常用的日期时间处理方法。

在前端可以通过new Date()生成Date对象,如果没有传参数时,即获取本地当前日期和时间。不过这时候显示的内容并不是我们常见的日期格式,而是一个当前时区时间的描述文本,以下代码显示的效果如图所示:

  const date = new Date();
  console.log(date);
1260765-20221204184318695-43227495.png

如果希望显示的内容格式化为常见的日期格式,最简单的办法是调用 toLocaleString() 方法,如下所示:

  const date = new Date();
  console.log(date.toLocaleString());

1260765-20221204184405234-1817406876.png

new Date()可接受三种类型的参数

第一种是只传入一个number类型的参数,一般是时间戳的毫秒数,返回参数数字所处的时间,如下所示:

  const date = new Date(946684800000);
  console.log(date.toLocaleString());

第二种也只传入一个参数,参数类型是string,不过需要是正确的格式,如 "2010-10-10 10:10:10",返回对应的时间:

  const date = new Date("2010-10-10 10:10:10");
  console.log(date.toLocaleString());
第三种是可以传入多个参数,总共可传7个 number 类型的参数,分别是年,月(0~11),日,小时,分钟,秒钟,毫秒。这种方式的每一个参数值没有规定范围,Date对象会自动帮我们算出对应的时间。 比如我们传入的月是12,那么生成的日期会自动修正为第二年的1月。如下所示:
  const date = new Date(2022,12,1,10,10,10,999);
  console.log(date.toLocaleString());
Date对象还提供了很多方法,根据需要实现的功能,在下面列出一些常用的方法。
一、获取时间戳
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起到现在的总毫秒数。获取时间戳的方法挺多,常见的有如下几种:
最常用的 getTime 方法
  const date = new Date();
  console.log(date.getTime());
还有一种 Date.now() 方法,这是ECMAScript 5.1版本给Date对象增加的静态方法。Date.now的速度比getTime快一倍以上,应该是获取时间戳最快的方法。
console.log(Date.now());
valueOf方法是返回对象的原始值,在Date对象上也是返回时间戳,一般很少有人使用这个方法获取时间戳
  const date = new Date();
  console.log(date.valueOf());
最简单粗暴的方法,是直接把创建的Date对象转换为数字,+new Date(),不过性能更差一点
  const date = new Date();
  console.log(+date);

二、获取常用时间数据

Date对象可以分别获取到本地年、月、日、小时、分钟、秒钟、毫秒等数据,方法如下:
    date.getFullYear():获取年
    date.getMonth():获取月
    date.getDate():获取日
    date.getDay():获取一周的某一天(0~6)
    date.getHours():获取小时
    date.getMinutes():获取分钟
    date.getSeconds():获取秒
    date.getMilliseconds():获取毫秒
使用这些方法,可以灵活的显示日期时间格式,以下是一个格式化当前日期时间的函数:
  function formatDate(){
    // 创建日期对象
    const date = new Date();
    // 获取各日期/时间数据
    let year = date.getFullYear();
    let month = date.getMonth();
    let DD = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    let day = date.getDay();
    // 拼接日期时间为字符串
    let time = year + '年' + month + '月' + DD + '日 ' + hour + ':' + minute + ':' + second + ' 星期' + ['日','一','二','三','四','五','六',][day];
    return time
  }
  console.log(formatDate())
1260765-20221204184703901-1079600350.png

 三、设置日期时间

除了在创建Date对象时,通过参数获取到对应时间的Date对象,也可以设置Date对象的时间。
    date.setFullYear():设置年,setFullYear()可以传3个参数,其中第2个和第3个是可选的,分别是要设置的年,月,日;
    date.setFullYear():设置月,预期值是 0~11,-1 将设置为上一年的最后一个月、12 将设置为明年的第一个月。setMonth()可以传2个参数,其中第2个是可选的,分别是要设置的月,日;
    date.setDate():设置日,预期值是 1~31;0 会设置为上个月的最后一天、-1 将设置为上个月的最后一天的前一天、如果一个月有 31 天:32 将导致下个月的第一天;
    date.setHours():设置小时(0~23),setHours()可以传4个参数,其中第2、3、4个是可选的,分别是要设置的时,分,秒,毫秒;
    date.setMinutes():设置分钟(0~59),setMinutes()可以传3个参数,其中第2个和第3个是可选的,分别是要设置的分,秒,毫秒
    date.setSeconds():设置秒(0~59),setSeconds()可以传2个参数,其中第2个是可选的,分别是要设置的秒,毫秒
    date.setMilliseconds():设置毫秒(0~59)
使用设置日期方法,可以实现一些获取指定日期时间的功能。
如果要获取2020年的当前时间,就可以使用 setFullYear() 方法轻松实现,如下所示:
  const date = new Date();
  date.setFullYear(2020)
  console.log(date.toLocaleString());
又如获取今年二月的最后一天(即当月的天数):
  const date = new Date();
  date.setMonth(2,0);
  console.log(date.getDate());
再或者获取昨天和明天的日期:
  const date = new Date();
  date.setDate(date.getDate() + 1);
  console.log('明天是',date.toLocaleString());
  date.setDate(date.getDate() - 2);
  console.log('昨天是',date.toLocaleString());
在实际工作中,会经常需要获取到特定的日期。可以封装一个函数,用于获取当前日期的前n天或后n天
  function getSpecificDate(day){
    //计算出要加/减的毫秒数
    var num = 1000*60*60*24*day;
    var newDate = new Date(Date.now()+num);
    return newDate;
  }

  console.log('明天是',getSpecificDate(1).toLocaleString());
  console.log('后天是',getSpecificDate(2).toLocaleString());
  console.log('昨天是',getSpecificDate(-1).toLocaleString());
1260765-20221204184804658-105866816.png

 还有一种很方便的,给Date的原型方法中加入format方法,这样在Date对象上可以直接使用format方法格式化所需要的日期。如下所示:

  Date.prototype.format = function(format){
    var o =  {
    "M+" : this.getMonth()+1, //month
    "d+" : this.getDate(), //day
    "h+" : this.getHours(), //hour
    "m+" : this.getMinutes(), //minute
    "s+" : this.getSeconds(), //second
    "q+" : Math.floor((this.getMonth()+3)/3), //quarter
    "S" : this.getMilliseconds() //millisecond
    };
    if(/(y+)/.test(format)){
      format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(var k in o)  {
      if(new RegExp("("+ k +")").test(format)){
      format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
      }
    }
    return format;
  };
  console.log(new Date().format('yyyy-MM-dd hh:mm:ss'))
注: 在国内一般的项目都只需要获取本地时间就足够了,如果涉及到国外的项目,就可能需要获取世界标准时间。获取世界标准时间的方法就是在获取本地时间的方法中加上UTC,如 getUTCDate

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK