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.
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.
The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
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.
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);
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;
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With