js -- Date object attribute to obtain the current date + method detailed example

JavaScript Date object

Date objects are used to process dates and times.

How to use the Date() method to get the date of the current day.

getFullYear()
Use getFullYear() to get the year.

getTime()
getTime() returns the number of milliseconds since January 1, 1970.

setFullYear()
How to set a specific date using setFullYear().

toUTCString()
How to use toUTCString() to convert the date of the current day (according to UTC) into a string.

getDay()
How to use getDay() and arrays to display weeks, not just numbers.

Creation date

The Date object is used to process dates and times.

You can define a Date object with the new keyword. The following code defines a Date object named myDate:

There are four ways to initialize the date:

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

Most of the above parameters are optional. If they are not specified, the default parameter is 0.

Some examples of instantiating a date:

var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)

Set date

By using methods for date objects, we can easily manipulate dates.

In the following example, we set a specific date for the date object (January 14, 2010):

var myDate=new Date();
myDate.setFullYear(2010,0,14);

In the following example, we set the date object to the date after 5 days:

var myDate=new Date();
myDate.setDate(myDate.getDate()+5);

Note: if increasing the number of days will change the month or year, the date object will automatically complete this conversion.

Comparison of two dates
Date objects can also be used to compare two dates.

The following code compares the current date with January 14, 2100:

var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();

if (x>today)
{
    alert("Today is before January 14, 2100");
}
else
{
    alert("Today is after January 14, 2100");
}

How to format a date in the specified format?

Date.prototype.format = function(fmt){
  var o = {
    "M+" : this.getMonth()+1,                 //month
    "d+" : this.getDate(),                    //day
    "h+" : this.getHours(),                   //hour
    "m+" : 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;
}

document.getElementById("demo1").innerHTML=new Date(79,5,24,11,33,0).format("MM month dd day"); 

var now = new Date();
var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
document.getElementById("demo2").innerHTML=new Date().format("yyyy year MM month dd day");
var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
document.getElementById("demo3").innerHTML=new Date().format("yyyy year MM month dd day hh hour mm branch ss second");

Other format examples:

alert(new Date().format("yyyy year MM month dd day"));
alert(new Date().format("MM/dd/yyyy"));
alert(new Date().format("yyyyMMdd"));
alert(new Date().format("yyyy-MM-dd hh:mm:ss"));

The idea of the above method is great. The only drawback is that it is case sensitive. When calling, it can only follow the specified letter format, so it is added on the basis to make it case insensitive, so it is more flexible.

Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                   //month
    "d+": this.getDate(),                        //day
    "h+": this.getHours(),                       //hour
    "m+": this.getMinutes(),                     //branch
    "s+": this.getSeconds(),                     //second
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
    "S": this.getMilliseconds()                  //millisecond
  };

  //  Get year 
  // ①
  if (/(y+)/i.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }

  for (var k in o) {
    // ②
    if (new RegExp("(" + k + ")", "i").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}

var now = new Date();
var nowStr = now.format("YYYY-MM-DD"); // 2021-01-11

Keywords: Javascript

Added by exec1 on Sun, 16 Jan 2022 00:29:33 +0200