0

I have page with 2 textfields (start time and end time) i am using HTML5 time element, now i want to validate start time is always lesser than end time, i am currently using below script to validate

function checkTimings(source, argument) {
                    var sTime = new Date("01/01/0001 " + $("[id$=txtStartTimings]").val());
                    var eTime = new Date("01/01/0001 " + $("[id$=txtEndTimings]").val());
                    argument.IsValid = sTime < eTime;
                }

This work when the either both the timings are AM or PM but there's one case when the start time would be PM and end time would be AM like 11.45 PM to 12.15 AM, here the validation fails.

Could anyone suggest how we could handle this situation?

Abbas
  • 4,948
  • 31
  • 95
  • 161

2 Answers2

0

Is it possible to convert them to 24hrs format before doing the calculations?

function checkTimings(source, argument) {
                var sTime = new Date("01/01/0001 " + $("[id$=txtStartTimings]").GetHours());
                var eTime = new Date("01/01/0001 " + $("[id$=txtEndTimings]").GetHours());
                argument.IsValid = sTime < eTime;
            }
LuxuryWaffles
  • 1,518
  • 4
  • 27
  • 50
  • Even converting to 24hours didn't helped, because 11:45PM would get converted to 23:45 and 12:00AM to 00.00 now here again start time is greater than end time. – Abbas May 23 '17 at 06:11
  • what about, you do a check to see if it is in the time range you consider as the previous day and add +1 to the day if it falls in the range? – LuxuryWaffles May 23 '17 at 07:51
  • but here i am not dealing with the day, but just for the time, so user will just set the time, it could be any day, day is not the concerned here. – Abbas May 23 '17 at 08:30
  • yes, but isn't this situation caused by not differentiating if the 12AM belongs to the current or next day? Wouldn't it be better if you had a view that tells the user the date which the 12AM belongs or prefix your 24 hours as something like if in range of 12:00AM to 1:00AM, new Date("02/01/0001" + $("[id$=txtEndTimings]") so you count 12:00AM as the next day so in your calculation, sTime will be less than eTime – LuxuryWaffles May 23 '17 at 08:39
  • or if sTime = PM and eTime = AM, var eTime = new Date("02/01/0001 " + $("[id$=txtEndTimings]").val()); – LuxuryWaffles May 23 '17 at 08:47
0

You can directly pass date in data constructor to get actual date.

function checkTimings(source, argument) {
                    var sTime = new Date($("[id$=txtStartTimings]").val());
                    var eTime = new Date($("[id$=txtEndTimings]").val());
                    argument.IsValid = sTime < eTime;
            }

if problem persist then just change the format of your date in text field or you can also parse date in js function.

Zigri2612
  • 2,279
  • 21
  • 33