Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate timespan in JavaScript

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/2008 05:00:00

I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page.

like image 356
Ron Skufca Avatar asked Sep 26 '08 18:09

Ron Skufca


People also ask

What is TimeSpan in JavaScript?

TimeSpan(days : int, hours : int) Creates a TimeSpan from the specified amount of days and hours. TimeSpan( hours : int, minutes : int, seconds : int) Creates a TimeSpan from the specified amount of hours, minutes and seconds.

What is Date now () in JavaScript?

The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

Can JavaScript handle dates and time?

The Date object is a built-in object in JavaScript that stores the date and time. It provides a number of built-in methods for formatting and managing that data. By default, a new Date instance without arguments provided creates an object corresponding to the current date and time.


2 Answers

function stringToDate(string) {
        var matches;
    if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2}) (\d{2,2}):(\d{2,2}):(\d{2,2})$/)) {
       return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]);
    } else {
       return null;
    };
}

    function getTimeSpan(ticks) {
        var d = new Date(ticks);
        return {
            hour: d.getUTCHours(), 
            minute: d.getMinutes(), 
            second: d.getSeconds()
        }
    }

    var beginDate = stringToDate('2008-09-19 07:14:00');
    var endDate = stringToDate('2008-09-19 17:35:00');

    var sp = getTimeSpan(endDate - beginDate);
    alert("timeuse:" + sp.hour + " hour " + sp.minute + " minute " + sp.second + " second ");

you can use getUTCHours() instead Math.floor(n / 3600000);

like image 97
jassey Avatar answered Sep 29 '22 10:09

jassey


Once your textbox date formats are known in advance, you can use Matt Kruse's Date functions in Javascript to convert the two to a timestamp, subtract and then write to the resulting text box.

Equally the JQuery Date Input code for stringToDate could be adapted for your purposes - the below takes a string in the format "YYYY-MM-DD" and converts it to a date object. The timestamp (getTime()) of these objects could be used for your calculations.

stringToDate: function(string) {
    var matches;
    if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
       return new Date(matches[1], matches[2] - 1, matches[3]);
    } else {
       return null;
    };
}
like image 33
ConroyP Avatar answered Sep 29 '22 10:09

ConroyP