Samsung Electronics logo

Calculating Date and Time Information

Learning how to calculate and compare time and date information is a basic time management skill:

  1. To calculate the duration difference between 2 date or time events, use the difference() method of the TimeDuration object:

    /* Calculate event1.duration - event2.duration */
    var diff = event1.duration.difference(event2.duration);
    if (diff.length < 0)
       console.log("Event1 is longer than Event2.");
    else if (diff.length == 0)
       console.log("Event1 is as long as Event2.");
       console.log("Event1 is shorter than Event2.");
    The unit of the returned TimeDuration object is equivalent to the largest possible unit amongst the source parameter units while making sure that precision is not lost in the result. This implies that if, for example, a comparison is done between "1 hour" and "20 minutes", the result is displayed as 40 minutes, not 0.67 hour. Although the hour is a bigger unit than the minute, the result is more precise if presented in minutes.
  2. To compare 2 TimeDuration objects for equality, use the equalsTo() method:

    var d1 = new webapis.TimeDuration(60, "MINS");
    var d2 = new webapis.TimeDuration(1, "HOURS");
    var ret = d1.equalsTo(d2); /* Returns true */
  3. To check whether 1 TimeDuration object is shorter than another, use the lessThan() method:

    /* Check whether d1 is shorter than d2 */
    var d1 = new webapis.TimeDuration(1, "HOURS");
    var d2 = new webapis.TimeDuration(120, "MINS");
    var ret = d1.lessThan(d2); /* Returns true */
  4. To check whether 1 TimeDuration object is longer than another, use the greaterThan() method:

    /* Check whether d1 is longer than d2 */
    var d1 = new webapis.TimeDuration(2, "HOURS");
    var d2 = new webapis.TimeDuration(60, "MINS");
    var ret = d1.greaterThan(d2); /* Returns true */
  5. To add a predefined time to the current date, use the addDuration() method:

    /* Convert the current date to the date of the next day, at the same time */
    var now = webapis.time.getCurrentDateTime();
    var tomorrow = now.addDuration(new webapis.Timeduration(1,"DAYS");

    If the number of added time is negative, date or time is set to an earlier moment of time.