Working with Date and Time in JavaScript

If you have a requirement to get ShortDate (1/11/1900) and AM/PM time down to the second (2:12:27 PM) from a JavaScript Date object; use this Date prototype method "formatMMDDYYYY()" on the Date object:

 Date.prototype.formatMMDDYYYY = function(){  
 return (this.getMonth() + 1) +  
 '/' + this.getDate() +  
 '/' + this.getFullYear();  
 }  
 var time = new Date();  
 console.log(time.formatMMDDYYYY() + ' ' +  
 time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true })  
 );  

Say we want to calculate the number of days between two given dates. We can utilize this .js function:

 function getDays(firstDate,secondDate){  
  var startDay = new Date(firstDate);  
  var endDay = new Date(secondDate);  
  var millisecondsPerDay = 1000 * 60 * 60 * 24;  
  var millisBetween = startDay.getTime() - endDay.getTime();  
  var days = millisBetween / millisecondsPerDay;  
  // Round down.  
  return Math.floor(days);  
 }  
 alert(getDays(Date(), '1/1/2017'));  

Also, although not referenced above because I wanted to show pure/plain .js in the example, there are several .js libraries for Date operations. The most popular of which seems to currently be: https://momentjs.com/

Reference: https://stackoverflow.com/questions/2035699/how-to-convert-a-full-date-to-a-short-date-in-javascript/2035706

No comments: