A series of transformations and common methods of Date object

Keywords: Javascript Unix JSON

I found that we often encounter a series of operations about time in projects, such as calculating the days of difference between two dates, etc., so I plan to make a good arrangement for later projects to use.
Date object: used to process date and time
I. create Date object

var date1=new Date();//Parameter none, default current time
var date2=new Date(num);//Parameter is a number, return 1970-01-01 08:00:00+num(num is MS)
var date3=new Date(string);//Parameter is string, return the corresponding time
var date4=new Date(year, month, day, hours, minutes, seconds, milliseconds);//The parameter is year month day hour minute second millisecond, which returns the corresponding time


II. Common methods
1. get

date1.getDate();//Get the current day date1.getDay(); / / get the current day of the week 
date1.getFullYear();//Get the current year date1.getHours(); / / get the current hours
date1.getMinutes();//Get the current minutes date1.getMilliseconds(); / / get the current milliseconds    
date1.getMonth();//Get the current month - 1 date1. Getseconds(); / / get the current seconds
date1.getTime();//Get the number of milliseconds from 1970-01-01 to the current

2. setting

date1.setDate(num);//Set the current day date1.setFullYear(num); / / set the current year   
date1.setHours(num);//Set the current hour date1.setMinutes(num); / / set the current minute  
date1.setMonth(num);//Set the current month date1.setMilliseconds(num); / / set the current milliseconds 
date1.setSeconds(num);//Set the current seconds date1.setTime(num); / / return 1970-01-01+num (Num is milliseconds)

3. conversion

date1.toDateString();//Convert date part to string date1.toJSON(); / / convert date part to JSON
date1.toLocaleDateString();//Converts the Date part of the Date object to a string, based on the local time format.
date1.toLocaleTimeString();//Converts the time part of the Date object to a string, based on the local time format.
date1.toLocaleString();////Converts a Date object to a string based on the local time format.      
date1.toTimeString();//Convert time part to string

Conversion of time and time stamp
We need to understand the relationship between the two Everything about time (timestamp, Date, time standard, etc.)

1. Unix timestamp is defined as the total number of seconds from 00:00:00:00 (UTC) on January 1, 1970 to now.
2. The Date object provided in JavaScript can save all times as an integer (new Date(num)), representing the total number of milliseconds since 00:00:00, January 1, 1970.
These two points mean:
1) when using unix time stamp as a parameter, you need to multiply 1000 to get the millisecond number Date() object to receive it correctly. When getting time, you need to divide 1000 to get the time stamp.
2) in js, the accuracy of a timestamp can be determined by the length of the timestamp: accurate to 10 bits per second; accurate to 13 bits per millisecond.
3) it is easy to calculate a time axis with constant interval by using time stamp in js, or to calculate the specific date before or after a certain period of time by giving a time, or to compare the dates

Related examples
1. Convert Date to String of specified format

// 1-2 placeholders can be used for month (m), day (d), hour (h), minute (m), second (s), quarter (q),
// Year (y) can use 1-4 placeholders, MS (S) can only use 1 placeholder (is 1-3 digits)
 Date.prototype.Format = function (fmt) { 
    var o = {
        "m+": this.getMonth() + 1, //Month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "i+": this.getMinutes(), //branch
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //Millisecond
    };
    if (/(y+)/.test(fmt)){
       fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
       for (var k in o){
       if (new RegExp("(" + k + ")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
         }
       }
    }
     return fmt;
}
(new Date()).Format("yyyy-mm-dd hh:ii:ss.S");//2019-11-08 17:36:11.2
//In a regular expression, y is just a plain text to match the letter Y
// Y + means: match 1 to more than one y
// The meaning of Y + is: the content matched by Y + may be retrieved by grouping. Here, it is retrieved by the first grouping. As you can see from the following code, RegExp.  is the content of the y + matching

2. Get the current time of the previous days or the next days

 Date.prototype.AddDays = function (num) {
  if (isNaN(num) || num === null) {
    return this;
  }
  return new Date(this.getTime() + 24 * 60 * 60 * 1000 * num);
}
(new Date()).AddDays(-1).Format("yyyy-mm-dd")//2019-11-07
(new Date()).AddDays(2).Format("yyyy-mm-dd")//2019-11-10

3. Calculate the time difference between two dates

function differenceTime(date1,date2) { 
    var a=new Date(date1).getTime();
    var b=new Date(date2).getTime();
    iDays = parseInt(Math.abs(a - b) / 1000 / 60 / 60 / 24); //Convert the number of milliseconds of phase difference to days, and take the absolute value of Math.abs
    return iDays;
  }
differenceTime('2019-09-10','2019-10-10')//30

4. Compare before and after two times

//True > d1 > d2, d1 after d2, false > d1 < d2, d1 before d2
function CompareDate(d1, d2) {
  return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
}
 CompareDate('2019-11-11 12:22','2018-11-11 12:22')//true

Posted by Mr.x on Fri, 08 Nov 2019 03:09:35 -0800