February 21, 2001 - Debugging Date-Based Scripts | WebReference

February 21, 2001 - Debugging Date-Based Scripts

Yehuda Shiran February 21, 2001
Debugging Date-Based Scripts
Tips: February 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Debugging a script for date handling and manipulation is not trivial. Your script usually starts with today's Date object, but you want to test your script for other days as well. You can accomplish it by setting the Date object's date. You can go forward or backward in time, by using the object's setTime() method. This method expects to get the number of milliseconds since 1970. The easiest way to compute it is by adding or subtracting from the current time. The current time is computed by the object's getTime() method. To set the Date object to the day before yesterday, you would write:

  now.setTime(now.getTime() - 2 * 24 * 60 * 60 * 1000);
Once you set the Date object to whatever date you want, you can debug your script as if the current day is two days ago. For example, you can test the function getDeliveryDateObj(), mimicking the day before yesterday as the current date:

function getDeliveryDateObj(businessDaysLeftForDelivery) {
  var now = new Date();
  now.setTime(now.getTime() - 2 * 24 * 60 * 60 * 1000);
  var dayOfTheWeek = now.getDay();
  var calendarDays = businessDaysLeftForDelivery;
  var deliveryDay = dayOfTheWeek + businessDaysLeftForDelivery;
  if (deliveryDay >= 6) {
    businessDaysLeftForDelivery -= 6 - dayOfTheWeek;  //deduct this-week days
	calendarDays += 2;  //count this coming weekend
	deliveryWeeks = Math.floor(businessDaysLeftForDelivery / 5); //how many whole weeks?
	calendarDays += deliveryWeeks * 2;  //two days per weekend per week
  }
  now.setTime(now.getTime() + calendarDays * 24 * 60 * 60 * 1000);
  return now;
}

Click here to get the delivery date in 8 business days, starting from the day before yesterday.