Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to display Date and Time in 12-hour format in Business Rule

gregcoogan
Kilo Explorer

I am writing a Business Rule to build a calculated field by concatenating some fields. I have already modified a date and time field with this code:

var tz = Packages.java.util.TimeZone.getTimeZone("America/Chicago");      

  var time = new GlideDateTime();      

  time.setTZ(tz);

  time.setValue(current.begin);  

  time.setValue(current.end);

This was to fix the time zone difference.

However, for end users, I would prefer to display the date and time in a 12-hour format instead of the 24-hour format, which would include AM and PM at the end. I have done a lot of research but haven't found any functionality that could convert the format. I figure I could code it to build the 12-hour format using conditional statements based on what the time value was, but that would be a bit messy. Is there another way?

1 ACCEPTED SOLUTION

James_Neale
Mega Guru

There is no easy way to do this other than taking the string value and writing a small script to replace the hours and add the appropriate AM/PM designator. (There are ways, but they use Java and are restricted in SN).



You can try something like this:



function convertDateTo12HourFormat(isoDateStr) {


  return isoDateStr.replace(/([^\s]+\s)(\d{2})(.+)/, function(x, date, h, ms) {


      h = parseInt(h, 10);


      var ampm = h > 11 ? 'PM' : 'AM';


      if (h > 12) h = h - 12;


      if (10 > h) h = '0' + h;


      return date + h + ms + ' ' + ampm;


  });


}



convertDateTo12HourFormat('2015-06-12 18:52:34'); // 2015-06-12 06:52:34 PM



Let me know if it needs explaining.


View solution in original post

5 REPLIES 5

Taufique Ahmed
Kilo Contributor

Hi James,



Thanks for this - was looking for a way to exctract a date to AM/PM format using the GlideDateTime functions and   not sure why SN have not made this availlable??


Was about to post a request in the community for this, but luckily came across this.



Cheers.