
Date.getDate() Method
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Alphabetical Language Reference
|
507
// Takes any Date object and returns a string of the format:
// Saturday December 16
function formatDate (theDate) {
var months = ["January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"];
var dateString = days[theDate.getDay()] + " "
+ months[theDate.getMonth()] + " "
+ theDate.getDate();
return dateString;
}
now = new Date();
trace("Today is " + formatDate(now));
The next example shows how to convert the 24-hour clock return value of getHours() to a
12-hour clock with AM and PM:
// Takes any Date object and returns a string of the format:
// "2:04PM"
function formatTime (theDate) {
var hour = theDate.getHours();
var minute = theDate.getMinutes() > 9 ?
theDate.getMinutes() : "0" + theDate.getMinutes();
if (hour > 12) {
var timeString = (hour - 12) + ":" + minute + "PM";
} else {
var timeString = hour + ":" + minute + "AM";
}
return timeString;
}
now = new Date();
trace("The time is " + formatTime(now));
For an example that uses the Date class to create an analog-style clock, see “Building a
Clock with Clips” in Chapter 13. Note that programming time-based behavior, such as ...