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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business