devxlogo

Compares a given date with today and inserts a text expression in a narrative JavaScript

Compares a given date with today and inserts a text expression in a narrative JavaScript

Demo of compdate

function TimeString(adate){  var tstring = "";  var aret = adate.getHours();      if (aret          tstring = "0";      tstring = tstring + aret;      aret = adate.getMinutes();      if (aret          tstring = tstring + "0";      tstring = tstring + aret;      aret = adate.getSeconds();      if (aret          tstring = tstring + "0";      tstring = tstring + aret;      return tstring;}function compDate(parm1) {   var mystring="";   var date1 = new Date(parm1);   var date2 = new Date();if (TimeString(date2)    date2.setTime(date2.getTime() - 86400000);  // Subtracts a day if necessary if time of event less than time now.var y1 = date1.getYear();var m1 = date1.getMonth();    m1++;var d1 = date1.getDate();var m1_max = 31;    if ((m1 == 4) || (m1 == 6) || (m1 == 9) || (m1 == 11))      m1_max = 30;    else if (m1 == 2)      m1_max = ((y1 % 4) ? 28 : 29);var y2 = date2.getYear();var m2 = date2.getMonth();    m2++;var d2 = date2.getDate();var m2_max = 31;    if ((m2 == 4) || (m2 == 6) || (m2 == 9) || (m2 == 11))      m2_max = 30;    else if (m2 == 2)      m2_max = ((y2 % 4) ? 28 : 29);var dDay = d2 - d1;    if ((d1 == m1_max) && (d2 == m2_max))  // If both days were last of the month, assume no difference.      dDay = 0;if (dDay     dDay = dDay + m1_max;   m2 = m2 - 1;  }var dMonth = m2 - m1;if (dMonth     dMonth = dMonth + 12;   y2 = y2 - 1;  }var dYear = y2 - y1;if (dYear) {   mystring +=dYear + " year";   if (dYear != 1)     mystring +="s"; }else    mystring +="less than a year";document.write(mystring);}I've been working at Creative Kousins forcompDate("August 29, 2011") and have been married to Susan forcompDate("Jun 13, 2002").  We have two boys who arecompDate("May 3, 2005")old andcompDate("August 29, 2011")old.  The best thing about working at Creative Kousins is ....... 
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist