extracting hour from a date time value

deepika46
Tera Contributor

Hello experts,

 

i have a date time value '

2024-06-01 08:00:00  

I want to extract the hour from it which is 08.(Should return 08)

 

Can anyone help me how to do it in a script. I am new to ServiceNow Scripting. Thanx in advance. 

2 ACCEPTED SOLUTIONS

here you go

var gdt = new GlideDateTime ("2017-03-31 15:13:43");
var gdtsplit = gdt.getDisplayValue().split(' ')[1].split(':');
year = gdt.getYearUTC();
month = gdt.getMonthUTC();
day = gdt.getDayOfMonthUTC();
var hour = gdtsplit[0];
var minute = gdtsplit[1];

gs.print('year = '+ year);
gs.print('month = '+ month );
gs.print('day = '+ day );
gs.print('hour = '+ hour );
gs.print('minute = '+ minute );
-Anurag

View solution in original post

Harsh Vardhan
Giga Patron

Hi @deepika46 

use getValue() instead getDisplayValue() , this will solve your requirement.  You will get correct hrs number. 

eg:

 

var gdt = new GlideDateTime ("2024-06-01 08:00:00");
var gdtsplit = gdt.getValue().split(' ')[1].split(':');
var hour = gdtsplit[0];
gs.print(hour)

 

Thanks,

Harsh

 

View solution in original post

12 REPLIES 12

Anurag Tripathi
Mega Patron
Mega Patron

Hi,

this should work

var gdt = new GlideDateTime ("2017-03-31 15:13:43");
var gdtsplit = gdt.getDisplayValue().split(' ')[1].split(':');
var hour = gdtsplit[0];
gs.print(hour)
-Anurag

Hello @Anurag Tripathi ,

 

Thank you so much. If i want to extract the month date as well. For example in the above example, if i want to retrieve 31. Then could plz tell me how to get that. 

here you go

var gdt = new GlideDateTime ("2017-03-31 15:13:43");
var gdtsplit = gdt.getDisplayValue().split(' ')[1].split(':');
year = gdt.getYearUTC();
month = gdt.getMonthUTC();
day = gdt.getDayOfMonthUTC();
var hour = gdtsplit[0];
var minute = gdtsplit[1];

gs.print('year = '+ year);
gs.print('month = '+ month );
gs.print('day = '+ day );
gs.print('hour = '+ hour );
gs.print('minute = '+ minute );
-Anurag

Hello @Anurag Tripathi ,

 

hour is printing wrong. can you please check. it is giving output as 17