Home > Web Front-end > JS Tutorial > Commonly used encapsulation methods for Date objects and solutions to problems encountered

Commonly used encapsulation methods for Date objects and solutions to problems encountered

不言
Release: 2019-03-21 11:06:52
forward
1945 people have browsed it

The content this article brings to you is about the commonly used encapsulation methods of Date objects and solutions to problems encountered. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I have been using the Date object in JS for a long time, but I have never recorded the commonly used encapsulation functions and pitfalls encountered. I will record them when I have time today so that I can use them directly next time. , and remind yourself of those pitfalls you have encountered. If there is something wrong, I hope you can point it out, I will be very grateful.

When converting a date (without hours, minutes and seconds) to a timestamp, the date is converted to a time when connected with '-' (2019-01-01) and '/' (2019/01/01) The results of the poke are different

In order to prevent everyone from seeing too many examples and getting bored, I will come to the conclusion first.
Conclusion:
1) If the dates are connected using '-', when the month and day are both less than 9 and a 0 is added in front, then the time will be converted to a timestamp by default 8 o'clock in the morning of the day
2) If the dates are connected using '-', when the month and day are less than 9 and there is a 0 in front of less than 9, then it will be converted to a timestamp. The time is converted to 8 a.m. of the day by default
3) If the dates are connected using '-', when the month and day are both less than 9 and only one is preceded by a 0, then it will be converted to a timestamp The time will be converted to 12 o'clock in the morning of the day by default, which is 00:00
4) If the dates are connected using '-', when the month and day are both greater than 9, then it will be converted to a timestamp The time will be converted to 8 a.m. of the day by default
5) If the dates are connected using '/', then when converted into timestamps, they will only be converted to 00:00 a.m. of the day
Summary: In When converting dates to timestamps, if the hours and minutes are not set, it is best to use '/' to connect to avoid obtaining different timestamps for the same date when written in different ways
The following is an example to prove the conclusion:

"
    let time1 = new Date('2019-03-03').getTime();
    let time2 = new Date('2019/3/3').getTime();
    console.log('获取时间')
    console.log(time1)        
    console.log(time2) 
    console.log( (time1-time2) / 1000 /60 /60 )       // 8
    // 根据本地格式,把Date对象的时间转换为字符串  上午12:00:00也就是 00:00:00
    console.log(new Date('2019-03-03').toLocaleString())  // 2019/3/3 上午8:00:00
    console.log(new Date('2019-03-12').toLocaleString())  // 2019/3/12 上午8:00:00
    console.log(new Date('2019-11-03').toLocaleString())  // 2019/11/3 上午8:00:00
    console.log(new Date('2019-3-03').toLocaleString())  // 2019/3/3 上午12:00:00
    console.log(new Date('2019-03-3').toLocaleString())  // 2019/3/3 上午12:00:00
    console.log(new Date('2019-11-13').toLocaleString()) // 2019/11/13 上午8:00:00
    console.log(new Date('2019/03/03').toLocaleString())  // 2019/3/3 上午12:00:00
    console.log(new Date('2019/3/3').toLocaleString())  // 2019/3/3 上午12:00:00
    console.log(new Date('2019/03/3').toLocaleString())  // 2019/3/3 上午12:00:00
    console.log(new Date('2019/3/03').toLocaleString())  // 2019/3/3 上午12:00:00
    console.log(new Date('2019/03/12').toLocaleString())  // 2019/3/12 上午12:00:00
    console.log(new Date('2019/11/03').toLocaleString())  // 2019/11/3 上午12:00:00
  "
Copy after login

Convert date format to timestamp and timestamp to date format

1. 将日期格式转换为时间戳的三种方法
   "javascript
    let dateStr = new Date('2019-3-20 18:59:39:123');
    let timestamp1 = dateStr.getTime();    // 1553079579123
    let timestamp2 = dateStr.valueOf();    // 1553079579123
    let timestamp3 = Date.parse(dateStr);  // 1553079579000
   "
date.getTime()、date.valueOf()会精确到毫秒,而Date.parse(date)只能精确到秒,毫秒用000替代
2. 将时间戳转换为日期格式
    "javascript
    function dateFormat(timestamp) {
        timestamp = (timestamp + '' ).length > 10 ? timestamp : timestamp * 1000;  //判断时间戳为几位,10位时加上毫秒,13为的则不管
        let date = new Date(timestamp);
        let year = date.getFullYear();
        let month = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);   // 月份从0开始,0~11, 所以显示时要 +1
        let day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate() ;
        let hour = date.getHours() > 9 ? date.getHours() : '0' + date.getHours() ;
        let minutes = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes();
        let seconds = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds();
        return year + '-' + month + '-' + day + ' ' + hour + ':' +  minutes + ':' + seconds;
    }
    "
Copy after login

Compare how many days are between two dates

/**
   * @method  计算两个日期之间有几天,包括第一天
   * @param  beginTime  开始时间的日期 '2019-3-19' || '2019/3/19'
   * @param  endTime    结束时间的日期 '2019-3-20' || '2019/3/19'
   */
getIntervalDay('2019-03-03', '2019-03-8');  // 若是没有用 正则将格式转换的话得到的结果是5天,转换后是6天
function getIntervalDay(beginTime, endTime) {
    // 先利用将其转换为统一的格式,因为 '-' 格式下的时间戳转换的结果不一致,原因在本文的开头
    beginTime = beginTime.replace(/\-/g, '/');
    endTime = endTime.replace(/\-/g, '/');
    let time1 = new Date(beginTime).getTime();
    let time2 = new Date(endTime).getTime();
    // console.log(beginTime)
    // console.log(endTime)
    let second = time2 - time1;
    let day = parseInt(second / (1000 * 60 * 60 * 24)) + 1; // 当天也算进去
    return day;
}
Copy after login

Judge how many days there are in a year Days

    // 闰年为366天(2月中多一天),平年为365天。
   // 闰年有两种: 1)普通闰年:能被4整除但不能被100整除的年份为普通闰年。
   //            2)世纪闰年:能被400整除的为世纪闰年。
   function getYearAllDay(year) {
       return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365;
   }
Copy after login

Get the total number of days in a month in a certain year

  // date格式为 'xxxx-xx-xx' 'xxxx/xx/xx' 'xxxx/xx' 'xxxx-xx'  
  function getMonthAllDay(date) {
      date = new Date(date);
      let year = date.getFullYear();
      let month = date.getMonth() + 1; // 从 Date 对象返回月份 (0 ~ 11)。 
      let nextMonth = year + '-' + (month + 1);  
      let newDate = new Date(nextMonth);
      newDate.setDate(0); // 利用设置日期时从1~31设置,当设置为0时,即上个月的最后一天
      return newDate.getDate();
  }
Copy after login
This article has ended here. For more other exciting content, you can pay attention to the JavaScript tutorial video# on the PHP Chinese website. ##Column!

The above is the detailed content of Commonly used encapsulation methods for Date objects and solutions to problems encountered. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template