Example analysis of javascript date comparison method

  • 2021-06-28 11:16:35
  • OfStack

An example of the javascript date comparison method is given in this paper.Share it for your reference, as follows:

Today in order to achieve such a function - the user can enter the date manually, but the date can only be entered before today, the time after today cannot be submitted, that is, today is the 15th, only the date before 15th, and the date after 15th cannot be entered


/**
  String as yyyyMMdd Convert formatted string to date type 
 date Is the date string 
*/
function getDate(date){
 var year = date.substr(0,4);//substr() From 0 Beginning of calculation 
 var month = date.substr(4,2);// Month is 0 reach 11 Months 
 var day = date.substr(6,2);
 alert(year+"-"+month+"-"+day);
 return new Date(year,month,day);
}
var date = getDate("20120704");
var date2 = getDate("20120720");
//alert(date.getTime());
//alert(date2.getTime());
alert(date2.getTime() - date.getTime())

Method 2 (including minutes and seconds)


var d1=new Date("2004/09/16 20:08:00");
var d2=new Date("2004/09/16 10:18:03");
// What you get is the time difference between the two 
var d3=d1-d2;
//alert(d1.getTime());
//alert(d2.getTime());
// The result of the information that pops up below is 1 Sample 
alert(d3);
alert(d1.getTime()-d2.getTime());

The third way (you can exclude minutes and seconds)


var d1=new Date("2004/09/17");
var d2=new Date("2004/09/16");
// What you get is the time difference between the two 
var d3=d1-d2;
//alert(d1.getTime());
//alert(d2.getTime());
// The result of the information that pops up below is 1 Sample 
alert(d3);
alert(d1.getTime()-d2.getTime());

PS: An online timestamp conversion tool is provided here, which contains table descriptions of timestamp operation methods in several common programming languages, including javascript, php, java, Python, C#etc. It is believed that this tool will be used in future programming development:

Unix timestamp (timestamp) conversion tool:
http://tools.ofstack.com/code/unixtime

More readers interested in JavaScript-related content can view this site's topics: JavaScript Time and Date Operation Skills Summary, JavaScript Switching Special Effects and Skills Summary, JavaScript Find Algorithmic Skills Summary, JavaScript Animation Special Effects and Skills Summary, JavaScript Errors and Debugging Skills Summary, JavaScript Data Structure and Algorithmic Skills Summary, and so on.Summary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Operation Usage

I hope that the description in this paper will be helpful to everyone's JavaScript program design.


Related articles: