Time Field Comparison

Megha21
Tera Contributor

Hello All,

We have a requirement to compare current time with 2 time (not date/time) fields of custom table. If the current time is in between the above two time fields. We have used following logic which is mostly working fine but sometime not working fine for system time zone. Could anyone help me with this?

Logic used:

var currentTime = new GlideDateTime().getLocalTime().getDisplayValueInternal(); // Get Current Local Time
var begTime = new GlideDateTime(grHRAssociate.u_beginning_time).getLocalTime().getDisplayValueInternal();
var endTime = new GlideDateTime(grHRAssociate.u_end_time).getLocalTime().getDisplayValueInternal();

if ( currentTime >= begTime && currentTime <= endTime &&) {
agents.push(grHRAssociate.u_hr_associate.toString());
}

Thank you!

11 REPLIES 11

Sunjyot Singh
Kilo Guru

Hi,

 

Did you try using the "compareTo()" function to compare dates.

You can refer to this API:

https://developer.servicenow.com/print_page.do?release=paris&category=null&identifier=c_APIRef&modul...

and try to use this function:

find_real_file.png

find_real_file.pngFor your logic you can use this like:

var currentTime = new GlideDateTime() // Get Current Local Time
var begTime = new GlideDateTime("2020-08-01 12:00:00"); //Pass your begin time
var endTime = new GlideDateTime("2023-08-01 12:00:00"); //Pass your end time

var begTimeComparison = currentTime.compareTo(begTime);
var endTimeComparison = currentTime.compareTo(endTime);

if (begTimeComparison == 1 && endTimeComparison == -1) {
gs.info("Success");
}

 

 

If that doesn't work, try using getNumericValue() and then compare them the way you are comparing.

find_real_file.png

 

Thanks.

yes, we have tried using numeric value, however as our 2 custom fields are time field and not date/time so it is not working as expected
As current date time we are getting 2022-03-10 and time fields dates are 1970-01-01

 

Ohh, I missed that part. The above won't work then.

So, if for time fields we are getting it from 1970-01-01, can we try something like this?

var getCurrentTime = new GlideDateTime().getLocalTime().getDisplayValueInternal(); // Get Current Local Time
var currentTime = new GlideDateTime("1970-01-01 " + getCurrentTime);
var begTime = new GlideDateTime("1970-01-01 12:54:27");
var endTime = new GlideDateTime("1970-01-01 15:54:27");

var begTimeComparison = currentTime.compareTo(begTime);
var endTimeComparison = currentTime.compareTo(endTime);

if (begTimeComparison == 1 && endTimeComparison == -1) {
gs.info("Success");
}