Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1568 How can I find the last day of the month for any given month?

You are here: irt.org | FAQ | JavaScript | Date | Q1568 [ previous next ]

Try this which does this and much more:

<script language="JavaScript"><!--
var text = '<table border="0">';

var today = new Date();
/* Test dates */
//today = new Date(2000,2,29);
//today = new Date(1999,1,14);
/*************/

var MonthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

theYear = today.getYear();
if (theYear < 1000) theYear +=1900;

text += '<tr><td>Today</td><td>: '+today+'</td></tr>';

StartOfThisYear = new Date(theYear,0,1);
EndOfThisYear = new Date(theYear,11,31);

StartOfLastYear = new Date(theYear-1,0,1);
EndOfLastYear = new Date(theYear-1,11,31);

if (today.getMonth()==0) {
   StartOfLastMonth = new Date(theYear-1,11,1);
   EndOfLastMonth = new Date(theYear-1,11,MonthDays[11]);
}
else {
   StartOfLastMonth = new Date(theYear,today.getMonth()-1,1);
   LastMonth = today.getMonth()-1;
   DaysInLastMonth = MonthDays[LastMonth];
   if (LastMonth == 1) { // February
      if (theYear%400==0 || (theYear%4 == 0 && theYear%100!=0) ) DaysInLastMonth +=1;
   }
   EndOfLastMonth = new Date(theYear,today.getMonth()-1,DaysInLastMonth);
}

StartOfLastWeekMS = today.getTime() - ( 24*60*60*1000*(today.getDay()+6) );
StartOfLastWeek = new Date(StartOfLastWeekMS);
EndOfLastWeek = new Date(StartOfLastWeekMS+24*60*60*1000*6);

text += '<tr><td>StartOfLastYear </td><td>: '+StartOfLastYear +'</td></tr>';
text += '<tr><td>EndOfLastYear   </td><td>: '+EndOfLastYear   +'</td></tr>';
text += '<tr><td>StartOfThisYear </td><td>: '+StartOfThisYear +'</td></tr>';
text += '<tr><td>EndOfThisYear   </td><td>: '+EndOfThisYear   +'</td></tr>';
text += '<tr><td>StartOfLastMonth</td><td>: '+StartOfLastMonth+'</td></tr>';
text += '<tr><td>EndOfLastMonth  </td><td>: '+EndOfLastMonth  +'</td></tr>';
text += '<tr><td>StartOfLastWeek </td><td>: '+StartOfLastWeek +'</td></tr>';
text += '<tr><td>EndOfLastWeek   </td><td>: '+EndOfLastWeek   +'</td></tr>';

text += '</table>';
document.write(text);
//--></script>

©2018 Martin Webb