Calculate timespan in JavaScript

前端 未结 7 2063
刺人心
刺人心 2021-01-01 21:48

I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows:

txtStart.Text = 09/19/2008 07:00:00

txtEnd.Text = 09/19/200

7条回答
  •  青春惊慌失措
    2021-01-01 22:06

    I googled for calculating a timespan in javascript and found this question on SO; unfortunately the question text and actual question (only needing hours and minutes) are not the same... so I think I arrived here in error.

    I did write an answer to the question title, however - so if anyone else wants something that prints out something like "1 year, and 15 minutes", then this is for you:

    function formatTimespan(from, to) {
        var text = '',
            span = { y: 0, m: 0, d: 0, h: 0, n: 0 };
    
        function calcSpan(n, fnMod) {
            while (from < to) {
                // Modify the date, and check if the from now exceeds the to:
                from = from[fnMod](1);
                if (from <= to) {
                    span[n] += 1;
                } else {
                    from = from[fnMod](-1);
                    return;
                }
            }
        }
    
        function appendText(n, unit) {
            if (n > 0) {
                text += ((text.length > 0) ? ', ' : '') +
                    n.toString(10) + ' ' + unit + ((n === 1) ? '' : 's');
            }
        }
    
        calcSpan('y', 'addYears');
        calcSpan('m', 'addMonths');
        calcSpan('d', 'addDays');
        calcSpan('h', 'addHours');
        calcSpan('n', 'addMinutes');
    
        appendText(span.y, 'year');
        appendText(span.m, 'month');
        appendText(span.d, 'day');
        appendText(span.h, 'hour');
        appendText(span.n, 'minute');
    
        if (text.lastIndexOf(',') < 0) {
            return text;
        }
    
        return text.substring(0, text.lastIndexOf(',')) + ', and' + text.substring(text.lastIndexOf(',') + 1);
    }
    

提交回复
热议问题