spacer
Yehuda Shiran October 22, 1999
Implementing Relative Times
Tips: October 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

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

Let's use the Date object to compute the day and the date of an event, using the time difference between the event and the current date. Suppose you want to know the date 99 days ago. Since the time difference is computed in milliseconds, you need to subtract 99 * 24 * 60 * 60 * 1000 milliseconds from the current time. The current time is expressed as the number of milliseconds since January 1, 1970. The following script computes the day and the date 99 days ago:

var now = new Date();
now.setTime(now.getTime() - 99 * 24 * 60 * 60 * 1000);
var day = now.getDay();
var date = now.getDate();
var month = now.getMonth();
var year = now.getYear();
year += (year < 1900) ? 1900 : 0;

var days = new Array();
days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";

var months = new Array();
months[0] = "January";
months[1] = "February";
months[2] = "March";
months[3] = "April";
months[4] = "May";
months[5] = "June";
months[6] = "July";
months[7] = "August";
months[8] = "September";
months[9] = "October";
months[10] = "November";
months[11] = "December";

alert(days[day] + ", " + months[month] + " " + date + ", " + year);

Notice that Sunday is the first day of the week and its index is 0. Similarly, the first month of the year is January and its numeric value is 0 as well. Also be sure to notice the Y2K solution in the script.


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