This is the 0 th article I have participated in beginner’s Entry, a lot of panic, welcome you to comment in the comments section. · Dry goods at the end of the article 🍔.

Basic concept

The Date type of ECMAScript refers to java.util.date in earlier versions of Java. To do this, the Date type saves the Date as the number of milliseconds that have passed since midnight on January 1, 1970, Universal Time Coordinated (UTC). Using this storage format, the Date type can represent precisely 285616 dates before and after January 1, 1970.


How to use

grammar

To create a Date object, call the Date constructor using the new operator. Syntax:

new Date(a);new Date(value);
new Date(dateString);
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
Copy the code

This code is also the four basic forms of the Date() constructor, which can be used as follows:

  • No parameters

    If no arguments are provided, the newly created Date object represents the Date and time at the time of instantiation.

    new Date(a)// Mon Jul 05 2021 14:50:15 GMT+0800
    Copy the code
  • A Unix timestamp

    value

    A Unix timestamp that is an integer value representing the number of milliseconds since 00:00:00 UTC (the Unix Epoch) on January 1, 1970, ignoring leap seconds. If value is negative, it represents the date before 00:00:00 on January 1, 1970. Note that most Unix timestamp features are accurate only to the nearest second.

    new Date(1625467815913) //Mon Jul 05 2021 14:50:15 GMT+0800
    new Date(-1625467815913) //Sun Jun 30 1918 01:09:44 GMT+0800
    Copy the code
  • Timestamp string

    dateString

    A string value representing a date. The string should be recognized by the correct method of date.parse (). If dateString does not represent a date, then this method returns NaN. If you pass the string representing the Date directly to the Date constructor, Date calls date.parse () behind the scenes.

    new Date('the 2021-07-05 15:25:00')  //Mon Jul 05 2021 15:25:00 GMT+0800
    new Date('2021/07/05 15:25:00')  //Mon Jul 05 2021 15:25:00 GMT+0800
    new Date('Mon Jul 05 2021 15:25:00')  //Mon Jul 05 2021 15:25:00 GMT+0800
    Copy the code
  • Provide the date and time separately for each member

    When at least a year and month are provided, this form of Date() returns each member of the Date object from the following parameters. Members that are not provided will use the least possible value (1 for dates, 0 for others).

    Year indicates the integer value of the year. 0 to 99 maps to 1900 to 1999, with other values representing the actual years.

    MonthIndex is the integer value of a month from 0 (January) to November (December). MonthIndex is calculated from “0”, which means That January is “0” and December is “11”.

    Date Specifies the integer value of the day in a month, starting from 1. The default value is 1.

    Hours Optional integer value of the number of hours in a day (in the 24-hour system). The default value is 0 (midnight).

    Minutes Optional integer value of the minute part of a complete time, such as 01:10:00. The default value is 0.

    Seconds optionally represents the integer value of the second portion of a complete time, such as 01:10:00. The default value is 0.

    Milliseconds indicates an integer value representing the millisecond portion of a complete time. The default value is 0.

    new Date(2021.6.5.15.22.00)  //Mon Jul 05 2021 15:22:00 GMT+0800
    Copy the code

Pay attention to

Different browsers have many problems with the implementation of the Date type. For example, many browsers will choose the current date instead of the out-of-bounds date, so some browsers will interpret “January 32, 2019” as “February 1,2019.” Opera inserts the current date before the current month and returns “January current date, 2019”. That is, if you run the code on September 21, it will return “January 21, 2019”.

attribute

  • Date.prototype

    Allows you to add properties to a Date object.

  • Date.length

    The value of date.length is 7. This is the number of arguments that the constructor can accept.

methods

  • Date.now()

    Returns the number of milliseconds since 1970-1-1 00:00:00 UTC. Is equivalent to new Date().gettime (), except that date.now () does not create additional Date objects.

    Date.now()  / / 1625473495744
    new Date().getTime()  / / 1625473495744
    Copy the code
  • Date.parse()

    Parses a string representing the date and returns the number of milliseconds since 1970-1-1 00:00:00.

  • Date.UTC()

    Takes the same arguments as the longest form of the constructor (from 2 to 7) and returns the number of milliseconds since 1970-01-01 00:00:00 UTC.

The Date instance

All Date instances inherit from date.prototype. Modifying the prototype object of the Date constructor affects all Date instances.

Instance attributes

  • Date.prototype.constructor

    Returns the constructor that created the instance. The default is the Date constructor.

Instance methods

Common instance methods are listed below, and more can be found at developer.mozilla.org/zh-CN/docs/…

Getter

  • Date.prototype.getDate()

    Returns the days (1-31) in the month of the specified date object based on local time.

  • Date.prototype.getDay()

    Returns the day of the week (0-6) of the specified date object based on local time.

  • Date.prototype.getFullYear()

    Returns the year of the specified date object based on local time (four digits for a four-digit year).

  • Date.prototype.getHours()

    Returns the hours (0-23) of the specified date object based on the local time.

  • Date.prototype.getMinutes()

    Returns the minutes (0-59) of the specified date object based on the local time.

  • Date.prototype.getMonth()

    Returns the month (0-11) of the specified date object based on the local time.

  • Date.prototype.getSeconds()

    Returns the number of seconds (0-59) of the specified date object based on the local time.

  • Date.prototype.getTime()

    Returns the number of milliseconds elapsed from 1970-1-1 00:00:00 UTC to that date, with a negative value for the time before 1970-1-1 00:00:00 UTC.

Setter

  • Date.prototype.setDate()

    Sets the day of the month for the specified date object based on local time.

  • Date.prototype.setFullYear()

    Sets the full year (four digits for a four-digit year) for the specified date object based on the local time.

  • Date.prototype.setHours()

    Sets the number of hours for a specified date object based on the local time.

  • Date.prototype.setMinutes()

    Sets the number of minutes based on the local time for a specified date object.

  • Date.prototype.setMonth()

    Sets the month based on the local time for the specified date object.

  • Date.prototype.setSeconds()

    Sets the number of seconds based on the local time for the specified date object.

  • Date.prototype.setTime()

    Set the time of a date object by specifying the number of milliseconds that have passed since 1970-1-1 00:00:00 UTC, or use a negative value for times earlier than 1970-1-1 00:00:00 UTC.


Common methods (all dry goods, welcome to comment area to add!!

According to the method provided by the Date instance, combined with the requirements of daily work, the following methods are summarized

  • Return an object that contains a variety of date formats. If you don’t have enough, you can add them yourself for easy management and reuse
function formatDate(dateStr){
        if(! dateStr) {return}
        let _date = dateStr

        if (typeof dateStr == 'string') {
            _date = new Date(str_date.replace(/-/g."/"))}if (typeof_date ! ='object') {
            return {};
        }

        // Add 0 when less than 10
        function fix(num) {
          return (String(num)).padStart(2.0)}// yyyy-MM-dd HH:mm:ss
        var year = _date.getFullYear()
            , month = _date.getMonth() + 1
            , date = _date.getDate()
            , day = _date.getDay()
            , hours = _date.getHours()
            , minutes = _date.getMinutes()
            , seconds = _date.getSeconds();

        var months = ['一月'.'二月'.'march'.'in April'.'may'.'June'.'July'.'August'.'September'.'October'.'November'.December]
            , months_en = ['January'.'February'.'March'.'April'.'May'.'June'.'July'.'August'.'September'.'October'.'November'.'December']
            , months_abbr = ['Jan'.'Feb'.'Mar'.'Apr'.'May'.'Jun'.'Jul'.'Aug'.'Sep'.'Oct'.'Nov'.'Dec']
            , days = ['Sunday'.'Monday'.'on Tuesday'.'on Wednesday'.'on Thursday.'on Friday'.'on Saturday]
            , days_en = ['Sunday'.'Monday'.'Tuesday'.'Wednesday'.'Thurday'.'Friday'.'Saturday']
            , days_abbr = ['Sun'.'Mon'.'Tue'.'Wed'.'Thu'.'Fri'.'Sat'];

        return {
            year: year,
            month: fix(month),
            date: fix(date),
            day: day,
            hours: fix(hours),
            minutes: fix(minutes),
            seconds: fix(seconds),
            month_name: months[month - 1].month_name_en: months_en[month - 1].month_abbr: months_abbr[month - 1].day_name: days[day],
            day_name_en: days_en[day],
            day_abbr: days_abbr[day],
            // yyyy-MM-dd
            ymd: year + The '-' + fix(month) + The '-' + fix(date),
            // yyyy.MM.dd
            ymd2: year + '. ' + fix(month) + '. ' + fix(date),
            // HH:mm:ss
            hms: fix(hours) + ':' + fix(minutes) + ':' + fix(seconds),
            // HH:mm
            hm: fix(hours) + ':' + fix(minutes),
            // yyyy-MM-dd HH:mm:ss
            full: year + The '-' + fix(month) + The '-' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes) + ':' + fix(seconds),
            // yyyy.MM.dd HH:mm:ss
            full2: year + '. ' + fix(month) + '. ' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes) + ':' + fix(seconds),
            // yyyy/MM/dd HH:mm
            ymdhm: year + '/' + fix(month) + '/' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes),
            // yy/MM/dd HH:mm
            ymdhm2: (year + ' ').substring(2.4) + '/' + fix(month) + '/' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes),
            // MM/dd HH:mm
            mdhm: fix(month) + '/' + fix(date) + ' ' + fix(hours) + ':' + fix(minutes),
            // dd month yyyy HH:mm
            west: fix(date) + ' ' + months_abbr[month - 1] + ' ' + year + ' ' + fix(hours) + ':' + fix(minutes)
        };
    }
 
formatDate(new Date())

/ / {
// date: "05"
// day: 1
// day_abbr: "Mon"
//     day_name: "周一"
// day_name_en: "Monday"
// full: "2021-07-05 17:05:02"
/ / full2: "2021.07.05 17:05:02"
// hm: "17:05"
// hms: "17:05:02"
// hours: "17"
// mdhm: "07/05 17:05"
// minutes: "05"
// month: "07"
// month_abbr: "Jul"
// month_name: "July"
// month_name_en: "July"
// seconds: "02"
// west: "05 Jul 2021 17:05"
// year: 2021
// ymd: "2021-07-05"
/ / ymd2: "2021.07.05"
// ymdhm: "2021/07/05 17:05"
// ymdhm2: "21/07/05 17:05"
/ /}

Copy the code
  • Return a copy ofThe start timeThe end of timeGets the shortcut key to the month of the datecurrentMounthLast month,prevMounthThis week,currentWeekLast week,prevWeek(Do not pass tag this month by default)
function getShortkeyDate(tag){
    const tempDate = new Date().getDate(); // The current date
    const tempDay = new Date().getDay() ? new Date().getDay() : 7; // Date of the current week
    const currentDate = new Date(a);// The current date
    let end = new Date(a);let start = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * (tempDate-1));
    if(tag == 'currentMounth'){ 
        end = new Date(a); start =new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * (tempDate-1));
    } else if(tag == 'currentWeek'){ 
        end = new Date(a); start =new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * (tempDay-1));
    } else if(tag == 'prevMounth'){
        end = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * tempDate);
        const endTempDate = new Date(end).getDate(); // What was the last day of last month
        start = new Date(end).setTime(new Date(end).getTime() - 3600 * 1000 * 24 * (endTempDate-1));
    } else if(tag == 'prevWeek'){ 
        end = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * tempDay);
        start = new Date().setTime(currentDate.getTime() - 3600 * 1000 * 24 * (tempDay-1+7));
    }
    return [new Date(start), new Date(end)]
}
      
getShortkeyDate('currentMounth')
//[Thu Jul 01 2021 17:30:11 GMT+0800, Mon Jul 05 2021 17:30:11 GMT+0800]
Copy the code
  • Gets the date in the last month of the current date, usually used to get the date in the last 30 days. Returns a string representing the date
function getPreMonth(date) {
    let arr = date.split(The '-');
    let year = arr[0]; // Get the year of the current date
    let month = arr[1]; // Get the month of the current date
    let day = arr[2]; // Get the date of the current date
    let days = new Date(year, month, 0);
    days = days.getDate(); // Get the number of days in the month in the current date
    let year2 = year;
    let month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    let day2 = day;
    let days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    let t2 = year2 + The '-' + month2 + The '-' + day2;
    return t2;
}
      
getPreMonth('2021-07-31')  / / "2021-06-30"
getPreMonth('2021-01-01')  / / "2020-12-01"
Copy the code
  • Get each day of two time periods, usually used for rendering diagrams, and determine if there is any data based on the date. If there is no data, create one, and return an array of dates for each day between the start time and the end time
function formatEveryDay(start, end) {
    let dateList = []; 
    let startTime = new Date(start);
    let endTime = new Date(end);

    while ((endTime.getTime() - startTime.getTime()) >= 0) {
        let year = startTime.getFullYear();
        let month = (String(startTime.getMonth() + 1)).padStart(2.0);
        let day = (String(startTime.getDate())).padStart(2.0);
        dateList.push(year + "-" + month + "-" + day); 
        startTime.setDate(startTime.getDate() + 1);
    }
    return dateList;
}
    
formatEveryDay('2021-07-01'.'2021-07-05')
/ / / "2021-07-01", "2021-07-02", "2021-07-03", "2021-07-04", "2021-07-05"]
Copy the code
  • Num = 0; num = 0; num = 0; num = 0
function getFormatXDate(num) { 
    let date = new Date(a); date.setDate(date.getDate() + num);let Y = date.getFullYear()
    let M = (date.getMonth() + 1) < 10? "0"+ (date.getMonth() + 1) : date.getMonth() + 1
    let D =  date.getDate()< 10? "0" + date.getDate() : date.getDate()
    let time = Y+"-"+M+"-"+D; 
    return time;
}

// The date of today
getFormatXDate(0)  / / "2021-07-05"
// Date after 4 days, the current date is 2021-07-05
getFormatXDate(4)  / / "2021-07-09"
// The date before 8 days
getFormatXDate(-8)  / / "2021-06-27"

Copy the code

conclusion

I don’t know if anyone can see the summary, just sprinkle water. · I always have the idea of writing articles, but I can’t output high-quality articles due to my poor writing style and my superficial knowledge in front end. However, I just stay in the step of creating new templates when I open Wolai for many times. On second thoughts or try it, everything is difficult at the beginning, slowly master the skills, write more good, rush.