Small example of JS controlling date display

  • 2020-03-29 23:57:49
  • OfStack

We generally encounter the problem of display time in the project. The general way to deal with it is to control the display time in the foreground through JS. The JS code to control the display time is as follows.


function Clock() {
 var date = new Date();
 this.year = date.getFullYear();
 this.month = date.getMonth() + 1;
 this.date = date.getDate();
 this.day = new Array(" Sunday ", " Monday ", " Tuesday ", " Wednesday ", " Thursday ", " Friday ", " Saturday ")[date.getDay()];
 this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
 this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
 this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
 this.toString = function() {
  return " Now it is :" + this.year + " years " + this.month + " month " + this.date + " day  " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day; 
 };//Now it is <SPAN id = clock> It's now: Wednesday, March 6, 2013 13:54:17 </ SPAN>


<SPAN></SPAN>
 this.toSimpleDate = function() {
  return this.year + "-" + this.month + "-" + this.date;
 };//2013-03-06

 this.toDetailDate = function() {
  return this.year + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second;
 };//2013-03-06 13:45:43

 this.display = function(ele) {
  var clock = new Clock();
  ele.innerHTML = clock.toString();//Display mode call
  window.setTimeout(function() {clock.display(ele);}, 1000);
 };
}


Related articles: