Time value (Time calculation)

A date and time algorithm.

Availability:

ECMAScript edition - 2
Property/method value type:Number primitive

The ECMA standard defines some useful methods for decomposing time values.

Some constant values need to be defined first:

From these we can derive some other values:

Now the methods can be defined in terms of these constants and their derivatives.

Example code:

   // 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);
   }

See also:Broken down time, Calendar time, Date object, MakeDate(), MakeDay(), MakeTime(), Time range, Universal coordinated time

Cross-references:

ECMA 262 edition 2 - section - 15.9.1.10

ECMA 262 edition 3 - section - 15.9.1.10