The ECMA standard defines some useful methods for decomposing time values.
Some constant values need to be defined first:
HoursPerDay = 24
MinutesPerHour = 60
SecondsPerMinute = 60
msPerSecond = 1000
From these we can derive some other values:
msPerMinute = msPerSecond * SecondsPerMinute = 60000
msPerHour = msPerMinute * MinutesPerHour = 3600000
Now the methods can be defined in terms of these constants and their derivatives.
HourFromTime(t) = floor(t / msPerHour) modulo HoursPerDay
MinFromTime(t) = floor(t / msPerMinute) modulo MinutesPerHour
SecFromTime(t) = floor(t / msPerSecond) modulo SecondsPerMinute
msFromTime(t) = t modulo msPerSecond
// Define some constants
HoursPerDay = 24;
MinutesPerHour = 60;
SecondsPerMinute = 60;
msPerSecond = 1000;
// Derived values
msPerMinute = msPerSecond * SecondsPerMinute;
msPerHour = msPerMinute * MinutesPerHour;
// Grab the time now in milliseconds
myMilliseconds = Number(new Date());
document.write("Hours ...: ");
document.write(HourFromTime(myMilliseconds));
document.write("<BR>");
document.write("Minutes ...: ");
document.write(MinFromTime(myMilliseconds));
document.write("<BR>");
document.write("Seconds ...: ");
document.write(SecFromTime(myMilliseconds));
document.write("<BR>");
document.write("Milliseconds ...: ");
document.write(msFromTime(myMilliseconds));
document.write("<BR>");
// Work out the hour number (Add 1 hour for BST)
function HourFromTime(aMillisecondTime)
{
return (Math.floor(aMillisecondTime/msPerHour) % HoursPerDay);
}
// Work out the minutes of the hour
function MinFromTime(aMillisecondTime)
{
return (Math.floor(aMillisecondTime/msPerMinute) % MinutesPerHour);
}
// Work out the seconds of the minute
function SecFromTime(aMillisecondTime)
{
return (Math.floor(aMillisecondTime/msPerSecond) % SecondsPerMinute);
}
// Work out the millisecond time value
function msFromTime(aMillisecondTime)
{
return (aMillisecondTime % msPerSecond);
}| Prev | Home | Next |
| Time range | Up | Time within day |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. | ||