Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Intermediate
Nov 13, 2015

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 for

compDate("August 29, 2011")

 and have been married to Susan for

compDate("Jun 13, 2002")

.  We have two boys who are

compDate("May 3, 2005")

old and

compDate("August 29, 2011")

old.  The best thing about working at Creative Kousins is ....... 
Warren Porter
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date