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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

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, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint