Combining Date and Time in JavaScript

Hi Experts,
JavaScript newbie!
I have a function which compares two times - start & finish (hh:mm) - gathered from 4 asp:dropdownlists (start hh, start mm, stop hh, stop mm).
However there is now a need to bring dates into the calculation so that if the start time is for example 22:00  today and the stop time is 02:00 tomorrow, the function will correctly calculate a duration of 4hrs and not 'think' that the stop time is before the start time.

I have included two calendar datepickers in the web form which write the selected dates to two asp:textboxes (startdate & enddate)

I presume I can access these as shown below but then I come a bit unstuck as how to enable the function to understand these as dates and bring them into the existing calculations:

var startdate = document.getElementById('<%=TxtStartDate.ClientID%>').value;

Open in new window


This is the function without dates - which works fine - you'll note just one date variable which isn't really used in the calc:

function TimeDuration() {
            var therate = document.getElementById('<%=DDLRate.ClientID%>').value;
            var date = document.getElementById('<%=TxtDate.ClientID%>').value;
            var starthours = document.getElementById('<%=DDLStartHrs.ClientID%>').value;
            var startmins = document.getElementById('<%=DDLStartMins.ClientID%>').value;
            var endhours = document.getElementById('<%=DDLStopHrs.ClientID%>').value;
            var endmins = document.getElementById('<%=DDLStopMins.ClientID%>').value;
             

            if (date != '' && starthours != '' && startmins != '' && endhours != '' && endmins != '') {
                // SPLIT INTO HOURS AND MIN
                //var ds = start.split(':');
                //var de = end.split(':');
                // WORK OUT DIFF IN MIN
                var diff = (starthours * 60 + startmins * 1) - (endhours * 60 + endmins * 1);
                //var diff = (de[0] * 60 + de[1] * 1) - (ds[0] * 60 + ds[1] * 1);
                // SET THE SIGN IF START > END
                var sign = (diff < 0) ? '' : '';

                // WORK WITH ABS VALUE
                diff = Math.abs(diff);

                // SET THE DIFF IN MINUTES
                //document.getElementById('mindiff').value = sign + diff;

                // CREATE A FORMATTED STRING hh:mm
                var hours = parseInt(diff / 60);
                var min = diff - (hours * 60);

                // LETS PAD THE STRING
                min = "00" + min;
                hours = "00" + hours;
                var hoursdecimal = "";
                var hoursrounded = "";
                var duration = sign + hours.substr(hours.length - 2) + ':' + min.substring(min.length - 2);

                
                if (duration.split(':')[1] >= '00' && duration.split(':')[1] <= '14') {
                    hoursdecimal = duration.split(':')[0] + ".00";
                    hoursrounded = duration.split(':')[0] + ":00";
                }

                if (duration.split(':')[1] >= '15' && duration.split(':')[1] <= '29') {
                    hoursdecimal = duration.split(':')[0] + ".25";
                    hoursrounded = duration.split(':')[0] + ":15";
                }

                if (duration.split(':')[1] >= '30' && duration.split(':')[1] <= '44') {
                    hoursdecimal = duration.split(':')[0] + ".50";
                    hoursrounded = duration.split(':')[0] + ":30";
                }

                if (duration.split(':')[1] >= '45' && duration.split(':')[1] <= '59') {
                    hoursdecimal = duration.split(':')[0] + ".75";
                    hoursrounded = duration.split(':')[0] + ":45";
                }

                // SET THE FORMATTED DIFF
                document.getElementById('<%=TxtDuration.ClientID%>').value = duration;
                // SET THE FORMATTED DIFF
                document.getElementById('<%=TxtDurationRounded.ClientID%>').value = hoursrounded;
                // SET THE FORMATTED DIFF
                document.getElementById('<%=TxtDurationDecimal.ClientID%>').value = hoursdecimal;


                if (therate == "2" && starthours != "--hh--" && startmins != "--mm--" && endhours != "--hh--" && endmins != "--mm--" && duration > "03:30") {
                    alert('Text goes here');
                    document.getElementById('<%=DDLStopHrs.ClientID %>').value = "";
                    document.getElementById('<%=DDLStopMins.ClientID %>').value = "";
                    document.getElementById('<%=TxtDuration.ClientID%>').value = "00:00";
                    document.getElementById('<%=TxtDurationRounded.ClientID%>').value = "00:00";
                    document.getElementById('<%=TxtDurationDecimal.ClientID%>').value = "00.00";
                }

                if (therate != "3" && starthours != "--hh--" && startmins != "--mm--" && endhours != "--hh--" && endmins != "--mm--" && duration < "01:00" && duration >= "00:00") {
                    alert('Text goes here)

                    document.getElementById('<%=DDLStopHrs.ClientID %>').value = "";
                    document.getElementById('<%=DDLStopMins.ClientID %>').value = "";
                    document.getElementById('<%=TxtDuration.ClientID%>').value = "00:00";
                    document.getElementById('<%=TxtDurationRounded.ClientID%>').value = "00:00";
                    document.getElementById('<%=TxtDurationDecimal.ClientID%>').value = "00.00";
                }

                //if (starthours != "--hh--" && startmins != "--mm--" && endhours != "--hh--" && endmins != "--mm--" ) {
                
                
                //}
            }
            var start = (starthours * 60 + startmins * 1);
            var end = (endhours * 60 + endmins * 1);

            if (starthours != "--hh--" && startmins != "--mm--" && endhours != "--hh--" && endmins != "--mm--" && start >= end) {

                alert('End time should be after start time.');
                document.getElementById('<%=DDLStopHrs.ClientID %>').focus();

            }


        }
    </script>

Open in new window


And this should give you an idea of what I'm trying to do (when you've stopped laughing some help would be really good) thanks in advance...

function TimeDuration() {
            var therate = document.getElementById('<%=DDLRate.ClientID%>').value;
            var startdate = document.getElementById('<%=TxtStartDate.ClientID%>').value;
            var enddate = document.getElementById('<%=TxtEndDate.ClientID%>').value;
           var starthours = document.getElementById('<%=DDLStartHrs.ClientID%>').value;
            var startmins = document.getElementById('<%=DDLStartMins.ClientID%>').value;
            var endhours = document.getElementById('<%=DDLStopHrs.ClientID%>').value;
            var endmins = document.getElementById('<%=DDLStopMins.ClientID%>').value;

            function parseDate(str) {
                var mdy = str.split('/')
                return new Date(mdy[2], mdy[0] - 1, mdy[1]);
            }

            function daydiff(startdate, enddate) {
                return (enddate - startdate) / (1000 * 60 * 60 * 24);
            }

            alert(daydiff(parseDate($('#startdate').val()), parseDate($('#enddate').val())));

            if (startdate != '' && starthours != '' && startmins != '' && enddate != '' && endhours != '' && endmins != '') {
                // SPLIT INTO HOURS AND MIN
                //var ds = start.split(':');
                //var de = end.split(':');
                // WORK OUT DIFF IN MIN
               var diff = (startdate + (starthours * 60 + startmins * 1)) - (enddate + (endhours * 60 + endmins * 1));
                //var diff = (de[0] * 60 + de[1] * 1) - (ds[0] * 60 + ds[1] * 1);
                // SET THE SIGN IF START > END
                var sign = (diff < 0) ? '' : '';

                // WORK WITH ABS VALUE
                diff = Math.abs(diff);

                // SET THE DIFF IN MINUTES
                //document.getElementById('mindiff').value = sign + diff;

                // CREATE A FORMATTED STRING hh:mm
                var hours = parseInt(diff / 60);
                var min = diff - (hours * 60);

Open in new window

forstersAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
There are a number of ways of solving this. The easiest is to use the JavaScript Date object.

var date1 = new Date(datestring1);
var date2 = new Date(datestring2);
var difference_in_hours = (date2 - date1) / (1000 * 3600);

Open in new window


The trick is how to get the date string into the correct ISO format the Date object requires.

The easiest way is to have your date picker return the values that allow you to create an ISO date string. This string looks like this
YYYY-MM-DDTHH:MM:SS.SSSZ

Open in new window


After that it is simple. If you want to use a different format for your date picker then you will have to manipulate the date string after you retrieve it from the text field so that it is in the format above.

Assuming the date string is in YYYY-MM-DD format you can create your date string as follows

var date1 = new Date(document.getElementById('<%TxtStartDate.ClientId%>').value + 'T' + document.getElementById('<%TxtStartHour.ClientId%>').value + ':' + document.getElementById('<%TxtStartMin.ClientId%>').value + ':00.000Z');

var date2 = new Date(document.getElementById('<%TxtEndDate.ClientId%>').value + 'T' + document.getElementById('<%TxtEndHour.ClientId%>').value + ':' + document.getElementById('<%TxtEndMin.ClientId%>').value + ':00.000Z');

// Calculate difference in hours
var difference = (date1 - date2) / (1000 * 3600);

Open in new window

The attached code demonstrates the concept using JQuery and Bootstrap Date picker a working sample is available here
t910.html
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
forstersAuthor Commented:
many thanks great answer exactly what I needed
0
Julian HansenCommented:
You are welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.