Wednesday, October 31, 2012

Subtracting days from a date in JavaScript and getting the day of the week in JavaScript isn't too tough.

The "BeginDate" conditional logic below shows how to roll a date backwards by 30 days.

function setPopupDate(targetID) {
   var dateInput = document.getElementById(targetID);
   var clockDate = new Date();
   if (targetID == FormFields.BeginDate) {
      clockDate.setDate(clockDate.getDate() - 30);
   }
   if (targetID == FormFields.EndDate) {
      var day = clockDate.getDay();
      clockDate.setDate(clockDate.getDate() - day);
   }
   var clockMonth = clockDate.getMonth() + 1;
   var clockDay = clockDate.getDate();
   var clockYear = clockDate.getFullYear();
   if (clockMonth < 10) {
      dateInput.innerHTML = "0" + clockMonth;
   } else {
      dateInput.innerHTML = clockMonth;
   }
   if (clockDay < 10) {
      dateInput.innerHTML = dateInput.innerHTML + "/0" + clockDay + "/" + clockYear;
   } else {
      dateInput.innerHTML = dateInput.innerHTML + "/" + clockDay + "/" + clockYear;
   }
}

 
 

The "EndDate" conditional logic above may be confusing. What am I attempting here?

var day = clockDate.getDay();
clockDate.setDate(clockDate.getDate() - day);

 
 

Well, per this, .getDay() will return a number which can be translated to a day of the week like so:

  1. Sunday
  2. Monday
  3. Tuesday
  4. Wednesday
  5. Thursday
  6. Friday
  7. Saturday

 
 

I want to roll the "EndDate" date back to the most recent Sunday, so subtracting a number of days equal to the encoding for the day of the week at hand should do the trick! On the JavaScript side, the controls I am handing this stuff too are ignorant of the time of day and the DateTime values that C# ultimately makes from strings all thus end up with midnight for the time of day. 12AM is the earliest possible moment in a day, but really I want the "EndDate" value to be at the other end of the time range within the Sunday specified. I thus do the following on the C# side. Here "endDate" is a string holding something like "10/31/2012" which can be translated into a DateTime value with a specific date but not a specific time of day. Midnight will be used as a default for the time of day.

DateTime end = Convert.ToDateTime(endDate);
end = end.AddDays(1);
end = end.AddSeconds(-1);

 
 

Bonus: In typing this up I learned how to change the inital digit of an ordered list to something other than the number one.

<ol start="0">
   <li>Sunday</li>
   <li>Monday</li>
   <li>Tuesday</li>
   <li>Wednesday</li>
   <li>Thursday</li>
   <li>Friday</li>
   <li>Saturday</li>
</ol>

No comments:

Post a Comment