#

# Q1127 How do I calculate the following dates based on todays date : StartOfLastYear, EndOfLastYear, StartofThisYear, EndOfThisYear, StartOfLastMonth, EndofLastMonth, StartofThisMonth, EndofThisMonth, StartofLastWeek, EndofLastWeek, StartofThisWeek, EndOfThisWeek?

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

Try:

```<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>```