Start time should be less than stop time

McJ
Tera Contributor

I have two single text line variables ( start_time and close_time) and having a script to collect the values in HH:MM AM/PM format.

something like this for start time

 

var pattern = /^(0?[1-9]|1[0-2]):([0-5][0-9]) (\\s)?([APap][mM])$/.test(newValue)

    if (!pattern) {

        g_form.setValue('start_time', '')

        alert("Time must be in HH:MM AM/PM format, please correct the value you entered to match the required format")

 

also has another client script for close_time too

 

Now need a script to compare these two values such that the start_time should be less than close_time when end user enter the values. How can I do that?

1 ACCEPTED SOLUTION

Shaheensk
Kilo Expert

Hi @McJ ,


Incorporating the following script in both client scripts might help


// Compare close_time and start_time
var startTime = g_form.getValue('start_time');
var closeTime = g_form.getValue('close_time');
if (startTime !== '' && closeTime !== '' &&  compareTimes(startTime, closeTime) >= 0) {
g_form.setValue('close_time', '');
alert("Close time must be greater than start time. Please correct the values.");
}

// Function to compare two times in HH:MM AM/PM format
function compareTimes(time1, time2) {
var date1 = new Date("2020-01-01 " + time1); //Some random date + time in HH:MM
var date2 = new Date("2020-01-01 " + time2);

return date1 - date2;
}

View solution in original post

3 REPLIES 3

Shaheensk
Kilo Expert

Hi @McJ ,


Incorporating the following script in both client scripts might help


// Compare close_time and start_time
var startTime = g_form.getValue('start_time');
var closeTime = g_form.getValue('close_time');
if (startTime !== '' && closeTime !== '' &&  compareTimes(startTime, closeTime) >= 0) {
g_form.setValue('close_time', '');
alert("Close time must be greater than start time. Please correct the values.");
}

// Function to compare two times in HH:MM AM/PM format
function compareTimes(time1, time2) {
var date1 = new Date("2020-01-01 " + time1); //Some random date + time in HH:MM
var date2 = new Date("2020-01-01 " + time2);

return date1 - date2;
}

McJ
Tera Contributor

I was able to fix it. 

Thanks

McJ
Tera Contributor

It works for me but let me ask another favor. Can we re-write the function without hard coding the dates here. (2020-01-01.)  I guess best practice is not to hard code dates into the script

use current date or something?