javascripttimedatejs

How to calculate hours greater than 24h using datejs


In table I have field type TIME where I am storing time interval e.g. 92:30:00, what I am trying to do with javascript (datejs) is to add or remove e.g. 02:15:00 to/from 92:30:00.

I am able to do it when the hours are not greater than 23:59 but how to do it when the values are over 23:59?

grab a from db //as 92:30
var b = Date.parse(a);
var c = Date.parse("02:15");

    d= new TimeSpan(b-c);
    e= (b).addHours(c);

console.log(d.toString("HH:mm")
console.log(e.toString("HH:mm")

as I sad it works If you stay in 24h time range, could it be possible to do the same with greater hours interval?

UPDATE: (sum them)

t = Date.today();
cc = Date.parse(c);
dd = Date.parse(d);

ccc = (cc - t)
ddd = (dd - t);

res = new TimeSpan(ccc+ddd);
console.log(res.toString()); //3.22:45:00

Solution

  • I don't think Datejs is going to parse a >24 hour time value correctly. The easiest work-around I can think of is just splitting the string into its parts and adding to Date.today().

    Here's a sample demonstrating the whole scenario.

    Example

    var a = '92:30'.split(':');
    var b = '02:15'.split(':');
    
    var c = Date.today().addHours(+a[0]).addMinutes(+a[1]);
    var d = Date.today().addHours(+b[0]).addMinutes(+b[1]);
    
    var e = new TimeSpan(c - d);
    
    console.log('days', e.days);  // 3
    console.log('hours', e.hours);  // 18
    console.log('minutes', e.minutes);  // 15
    

    I'm not 100% what you would like as an end result, but once you have the e TimeSpan you have the product of subtracting the two original values.

    Hope this helps.

    EDIT: If you just want to do simple math on the value to calculate an hours value, the following should work.

    Example

    var a = '92:30'.split(':');
    var b = '02:15'.split(':');
    
    var c = Date.today().addHours(+a[0]).addMinutes(+a[1]);
    var d = Date.today().addHours(+b[0]).addMinutes(+b[1]);
    
    var diff = (c - d) / (1000 * 60 * 60);
    
    console.log(diff); // 90.25
    

    You shouldn't require Datejs to do this though. Just using the native JavaScript Date API is all you need and you could remove any of Datejs API from the above sample.