Javascript Course

The function presented in this page, diffDateTime(), can be used to get the difference between 2 dates, time and date in JavaScript. This function receives two parameters: the start and ending datetime. It can be used various date / time formats: Unix Timestamp (in milliseconds), or a string containing an English datetime format. It can also be used a string with the words: NOW for current date-time, and TOMORROW for the next day (the 0:0:1 time); see in the examples presented after the code of this function.

Function to get the difference between 2 datetimes

Returns an object containing date and time difference: number of days, hours, minutes, seconds, total hours, total minutes, and total seconds (see the comments in code).
/* Function to calculate time difference between 2 datetimes (in Timestamp-milliseconds, or string English Date-Time)
 It can also be used the words: NOW for current date-time, and TOMORROW for the next day (the 0:0:1 time)
 Returns an object with this items {days, hours, minutes, seconds, totalhours, totalmin, totalsec}
*/
function diffDateTime(startDT, endDT){
 // JavaScript & jQuery Course - https://coursesweb.net/javascript/
  // if paramerer is string, only the time hh:mm:ss (with, or without AM/PM), create Date object for current date-time,
  // and adds hour, minutes, seconds from paramerer
  //else, if the paramerer is "now", sets Date object with current date-time
  //else, if the paramerer is "tomorrow", sets Date object with current date, and the hour 24 + 1 second
  // else create Date object with date time from startDT and endDT
  if(typeof startDT == 'string' && startDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}[amp ]{0,3}$/i)){
    startDT = startDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/);
    startDT = startDT.toString().split(':');
    var obstartDT = new Date();
    obstartDT.setHours(startDT[0]);
    obstartDT.setMinutes(startDT[1]);
    obstartDT.setSeconds(startDT[2]);
  }
  else if(typeof startDT == 'string' && startDT.match(/^now$/i)) var obstartDT = new Date();
  else if(typeof startDT == 'string' && startDT.match(/^tomorrow$/i)){
    var obstartDT = new Date();
    obstartDT.setHours(24);
    obstartDT.setMinutes(0);
    obstartDT.setSeconds(1);
  }
  else var obstartDT = new Date(startDT);

  if(typeof endDT == 'string' && endDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}[amp ]{0,3}$/i)){
    endDT = endDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/);
    endDT = endDT.toString().split(':');
    var obendDT = new Date();
    obendDT.setHours(endDT[0]);
    obendDT.setMinutes(endDT[1]);
    obendDT.setSeconds(endDT[2]);  
  }
  else if(typeof endDT == 'string' && endDT.match(/^now$/i)) var obendDT = new Date();
  else if(typeof endDT == 'string' && endDT.match(/^tomorrow$/i)){
    var obendDT = new Date();
    obendDT.setHours(24);
    obendDT.setMinutes(0);
    obendDT.setSeconds(1);
  }
  else var obendDT = new Date(endDT);

  // gets the difference in number of seconds
  // if the difference is negative, the hours are from different days, and adds 1 day (in sec.)
  var secondsDiff = (obendDT.getTime() - obstartDT.getTime()) > 0 ? (obendDT.getTime() - obstartDT.getTime()) / 1000 :  (86400000 + obendDT.getTime() - obstartDT.getTime()) / 1000;
  secondsDiff = Math.abs(Math.floor(secondsDiff));

  var oDiff = {};     // object that will store data returned by this function

  oDiff.days = Math.floor(secondsDiff/86400);
  oDiff.totalhours = Math.floor(secondsDiff/3600);      // total number of hours in difference
  oDiff.totalmin = Math.floor(secondsDiff/60);      // total number of minutes in difference
  oDiff.totalsec = secondsDiff;      // total number of seconds in difference

  secondsDiff -= oDiff.days*86400;
  oDiff.hours = Math.floor(secondsDiff/3600);     // number of hours after days

  secondsDiff -= oDiff.hours*3600;
  oDiff.minutes = Math.floor(secondsDiff/60);     // number of minutes after hours

  secondsDiff -= oDiff.minutes*60;
  oDiff.seconds = Math.floor(secondsDiff);     // number of seconds after minutes

  return oDiff;
}
- Examples diffDateTime() function Usage, with various date-time formats. The results will be added into a HTML element with id="testdtdiff".
<div id="testdtdiff"></div>
<script type="text/javascript"><!--
// Here add the diffDateTime() function

  /* 1.) Difference between 2 times (in hours:min:sec) */
var objDiff = diffDateTime('8:35:6', '8:55:34 AM');
var dtdiff = objDiff.days+ ' days, '+ objDiff.hours+ ' hours, '+ objDiff.minutes+ ' minutes, '+ objDiff.seconds+ ' seconds';
var total_hours = 'Total Hours: '+ objDiff.totalhours;
var total_min = 'Total minutes: '+ objDiff.totalmin;

// adds the result in #testdtdiff element
document.getElementById('testdtdiff').innerHTML += '1.) <b>"8:35:6", "8:55:34"</b><br/>Difference: '+ dtdiff+ '<br/>'+ total_hours+ '<br/>'+ total_min;

  /* 2.) Difference between a previous date-time and "now" (current datetime) */
var objDiff = diffDateTime('07/19/2012 14:10:00', 'now');
var dtdiff = objDiff.days+ ' days, '+ objDiff.hours+ ' hours, '+ objDiff.minutes+ ' minutes, '+ objDiff.seconds+ ' seconds';
var total_hours = 'Total Hours: '+ objDiff.totalhours;
var total_min = 'Total minutes: '+ objDiff.totalmin;

// adds the result in #testdtdiff element
document.getElementById('testdtdiff').innerHTML += '<br/><br/>2.) <b>"07/19/2012 14:10:00", "now"</b><br/>Difference: '+ dtdiff+ '<br/>'+ total_hours+ '<br/>'+ total_min;

  /* 3.) Difference between "now" (current datetime) and "tomorrow" (1st second in the next day) */
var objDiff = diffDateTime('NOW', 'TOMORROW');
var dtdiff = objDiff.days+ ' days, '+ objDiff.hours+ ' hours, '+ objDiff.minutes+ ' minutes, '+ objDiff.seconds+ ' seconds';
var total_hours = 'Total Hours: '+ objDiff.totalhours;
var total_min = 'Total minutes: '+ objDiff.totalmin;

// adds the result in #testdtdiff element
document.getElementById('testdtdiff').innerHTML += '<br/><br/>3.) <b>"NOW", "TOMORROW"</b><br/>Difference: '+ dtdiff+ '<br/>'+ total_hours+ '<br/>'+ total_min;

  /* 4.) Difference between 2 date nd time */
var objDiff = diffDateTime('August 25, 2012 14:10:00', '09/18/2012 08:25:00');
var dtdiff = objDiff.days+ ' days, '+ objDiff.hours+ ' hours, '+ objDiff.minutes+ ' minutes, '+ objDiff.seconds+ ' seconds';
var total_hours = 'Total Hours: '+ objDiff.totalhours;
var total_min = 'Total minutes: '+ objDiff.totalmin;

// adds the result in #testdtdiff element
document.getElementById('testdtdiff').innerHTML += '<br/><br/>4.) <b>"August 25, 2012 14:10:00", "09/18/2012 08:25:00"</b><br/>Difference: '+ dtdiff+ '<br/>'+ total_hours+ '<br/>'+ total_min;

  /* 5.) Difference between 2 date-time, with Timestamp (in milliseconds) */
var objDiff = diffDateTime(1348012438000, 1348029429000);
var dtdiff = objDiff.days+ ' days, '+ objDiff.hours+ ' hours, '+ objDiff.minutes+ ' minutes, '+ objDiff.seconds+ ' seconds';
var total_hours = 'Total Hours: '+ objDiff.totalhours;
var total_min = 'Total minutes: '+ objDiff.totalmin;

// adds the result in #testdtdiff element
document.getElementById('testdtdiff').innerHTML += '<br/><br/>5.) <b>1348012438000, 1348029429000</b><br/>Difference: '+ dtdiff+ '<br/>'+ total_hours+ '<br/>'+ total_min;
--></script>
To see the results of these examples, click

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Difference between two Dates - Time and Date

Last accessed pages

  1. Add, Change, and Remove Attributes with jQuery (46356)
  2. Node.js Move and Copy file (28419)
  3. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141747)
  4. Rectangle, Oval, Polygon - Star (3322)
  5. PHP PDO - prepare and execute (9187)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (471)
  2. CSS cursor property - Custom Cursors (78)
  3. The Mastery of Love (69)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)