tiagomacul
Giga Sage

how can we get hour, minute from a date field?

Sometimes we're facing some situations where a simple code could be a hard work because we're focused in our real demand therefore get a little samples from community it's realy useful and a fast way complete our mission.

 

The first things first, if you're here probaly you know something but sometimes no, so when we're coding something in date we have GlideDateTime()  API and to get a simple date:

var UDTDate = new GlideDateTime(); 
gs.log("date = " + UDTDate );

Sample result: "2021-03-08 16:24:06", "Instantiates a new GlideDateTime object from a date and time value in the UTC time zone specified with the format yyyy-MM-dd HH:mm:ss."


BUT, IF you're in a different timezone, you can be use

var MyDate = new GlideDateTime().getDisplayValue(); 
gs.log("My date = " + MyDate);

Sample result: "2021-03-08 14:24:06" (GMT-2) = From user

 

there's one more sample, returning date

//Now = Just a date
gs.log("now  = " + now());

Sample result: "08/03/2021"

 

However explained the context, how could i get hour separtily?

function timenow()
{
  var gdttime = new GlideDateTime(); 
  var time = gdttime.getTime();
  var timeCreated = time.getByFormat('HH:mm:ss');
  
  return timeCreated;
}

gs.log("UDT time now  = " + timenow());

Sample result "16:24:06"

additionally when we're talking about time zones

 

 

function timenow2()
{
  var gdttimeTmp = new GlideDateTime().getDisplayValue(); 
  var gdttime = new GlideDateTime(gdttimeTmp);
  var time = gdttime.getTime();
  var timeCreated = time.getByFormat('HH:mm:ss')
  
  return timeCreated;
}

OR
function timenow2()
{
  var gdttime = new GlideDateTime().getDisplayValue(); 
  var Dtsplit = gdttime.split(" ");
  var Timesplit = Dtsplit[1].split(":");
  var strTime = Timesplit[0] + ":" + Timesplit[1] + ":" + Timesplit[2]

  
  return strTime;
}
gs.log("My time now2  = " + timenow2());

Sample result "14:24:06"

 

image

Summary

Script Summary

 

Was useful, please leave your feedback!

 

Comments
indrasengupta
Tera Guru

if someone want's in AM/PM just add

var timeCreated = time.getByFormat('HH:mm:ss a')



Version history
Last update:
‎03-08-2021 08:33 AM
Updated by: