October 22, 1999 - Implementing Relative Times | WebReference

# October 22, 1999 - Implementing Relative Times

 October 22, 1999Implementing Relative Times Tips: October 1999 Yehuda Shiran, Ph.D.Doc JavaScript
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.