Dates Archives - ServiceNow Guru https://servicenowguru.com/tag/dates/ ServiceNow Consulting Scripting Administration Development Tue, 28 May 2024 20:26:22 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.2 https://servicenowguru.com/wp-content/uploads/2024/05/cropped-SNGuru-Icon-32x32.png Dates Archives - ServiceNow Guru https://servicenowguru.com/tag/dates/ 32 32 Client Side Dates in ServiceNow https://servicenowguru.com/client-scripts-scripting/client-side-dates-in-servicenow/ https://servicenowguru.com/client-scripts-scripting/client-side-dates-in-servicenow/#comments Wed, 22 Feb 2017 13:29:15 +0000 https://servicenowguru.wpengine.com/?p=12051 Dates on the client side in ServiceNow have always been challenging. Javascript has its own complexities in this regard and mixing this with ServiceNow’s date formats and user preferences can make it a nightmare. Here we walk through some of the methods of working with client side dates that make it MUCH simpler and allow

The post Client Side Dates in ServiceNow appeared first on ServiceNow Guru.

]]>
Dates on the client side in ServiceNow have always been challenging. Javascript has its own complexities in this regard and mixing this with ServiceNow’s date formats and user preferences can make it a nightmare.

Here we walk through some of the methods of working with client side dates that make it MUCH simpler and allow us to avoid the situation of having to return to the server via GlideAjax for most, if not all, date calculations.

ServiceNow Date Formats drop-down

If you’re here as a reference and just need the key code snippets, here you go. Basically, to get a javascript date from a ServiceNow date field value do this:

var date_number = getDateFromFormat(g_form.getValue('the_date_field'), g_user_date_format);
var my_date = new Date(date_number);

Or, from a Date/Time field do this:

var date_number = getDateFromFormat(g_form.getValue('the_date_time_field'), g_user_date_time_format);
var my_date = new Date(date_number);

The Details

Working with dates on the client side of things in ServiceNow has always been a challenge. Part of this is just due to Javascript and the challenges associated with dates and the other is ServiceNow. Given that users can have their own date format makes it even more challenging. That said, we are given some tools (albeit undocumented ones) that can help improve the situation.

I ran across some information a while back (thanks to John Roberts) that helps the situation drastically. The key comes down to a couple global variables defined by the system as well as function that helps use those variables.

The variables give us the date and datetime formats for the logged in user, and the function lets us use those to get something we can work with a little easier.

User datetime format: g_user_date_time_format
User date format: g_user_date_format

These used with the getDateFromFormat function gives us an easy way to get a value for the date (essentially a Unix Timestamp). That value can then be used directly or immediately passed into a Javascript Date object to allow for reformatting, testing, or whatever else is needed.

Here are a few functions that I put together to simplify the date validation process that is so often needed.

Test for valid DateTime based on user format:

function isValidDateTime(value){
  if(value == '' || value == undefined || value == null){
    return false;
  }
  return(getDateFromFormat(value, g_user_date_time_format) != 0);
}

Test for valid Date based on user format:

function isValidDate(value){
  if(value == '' || value == undefined || value == null){
    return false;
  }
  return (getDateFromFormat(value, g_user_date_format) != 0);
}

To take this a step further, you could easily add comparisons of dates or add custom date formats based on the values.

One thing to keep in mind with this, depending on where the date is coming from you may still have two date formats. Any of the dates that will work as shown are going to be the values in fields on a form or the Display Value of the date. If you’re getting something from the server (e.g. via GlideAjax) as just a value then it will be stored in the regular system format of YYYY-MM-DD HH:MM:SS.

An additional example suggested by a co-worker (thank Thomas) to validate that the date is within an hour

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
  if (isLoading || newValue == '') {
    return;
  }

  //To change the date range from 1 hour, change var minutes_from_now to desired amount time
  var minutes_from_now = 60;
  var date_obj = new Date(getDateFromFormat(newValue, g_user_date_time_format));
  var future_date = new Date(new Date().getTime() + minutes_from_now*60000);
  if(future_date < date_obj){
    alert("Time is too far out");
  }
}

Hopefully this helps save you some of the frustration I’ve experienced over the years when dealing with client side dates in ServiceNow.

The post Client Side Dates in ServiceNow appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/client-side-dates-in-servicenow/feed/ 5
Schedule-based Date/Time Addition https://servicenowguru.com/business-rules-scripting/schedule-time-addition/ https://servicenowguru.com/business-rules-scripting/schedule-time-addition/#comments Wed, 26 Oct 2011 15:53:50 +0000 https://servicenowguru.wpengine.com/?p=4076 I was recently asked to help a colleague figure out some date calculations based on a schedule. The requirement was to calculate a future date based on the existing value of a date/time field. I decided to document this solution (and come up with a solution for a similar problem…date addition from the current date/time

The post Schedule-based Date/Time Addition appeared first on ServiceNow Guru.

]]>
I was recently asked to help a colleague figure out some date calculations based on a schedule. The requirement was to calculate a future date based on the existing value of a date/time field. I decided to document this solution (and come up with a solution for a similar problem…date addition from the current date/time based on a schedule). Working with dates and schedules can really be a pain if you don’t have good examples to work from so hopefully these help somebody at some point. Read on for the full scripts.

These scripts are designed to work in a ‘before’ business rule. To get them to work in a UI action you need to include ‘current.update();’ as the last line.

Add time based on schedule to current time

//Get a schedule by name to calculate duration
var schedRec = new GlideRecord('cmn_schedule');
schedRec.get('name', '8-5 weekdays');
if (typeof GlideSchedule != 'undefined')
   var sched = new GlideSchedule(schedRec.sys_id);
else
   var sched = new Packages.com.glide.schedules.Schedule(schedRec.sys_id);

//Get the current date/time in correct format for duration calculation
var currentDateTime = new GlideDateTime();
currentDateTime.setDisplayValue(gs.nowDateTime());

//Set the amount of time to add (in seconds)
var timeToAdd = 86400;
durToAdd = new GlideDuration(timeToAdd*1000);
var newDateTime = sched.add(currentDateTime, durToAdd, '');

//Set the 'requested_by_date' field to the new date/time
current.requested_by_date = newDateTime;

Add time based on schedule to current field value

//Get a schedule by name to calculate duration
var schedRec = new GlideRecord('cmn_schedule');
schedRec.get('name', '8-5 weekdays');
if (typeof GlideSchedule != 'undefined')
   var sched = new GlideSchedule(schedRec.sys_id);
else
   var sched = new Packages.com.glide.schedules.Schedule(schedRec.sys_id);

//Get the current date/time in correct format for duration calculation
var currentDateTime = current.requested_by_date.getGlideObject();

//Set the amount of time to add (in seconds)
var timeToAdd = 86400;
durToAdd = new GlideDuration(timeToAdd*1000);
var newDateTime = sched.add(currentDateTime, durToAdd, '');

//Set the 'requested_by_date' field to the new date/time
current.requested_by_date = newDateTime;

The post Schedule-based Date/Time Addition appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/business-rules-scripting/schedule-time-addition/feed/ 25
Set Default Date/Time Picker Dialog Time https://servicenowguru.com/client-scripts-scripting/set-default-datetime-picker-dialog-time/ https://servicenowguru.com/client-scripts-scripting/set-default-datetime-picker-dialog-time/#comments Tue, 28 Jun 2011 14:39:49 +0000 https://servicenowguru.wpengine.com/?p=3857 H ave you ever wondered how you can change the default time displayed in a Date/Time dialog? In general, the Date/Time dialog is controlled by back-end code so there’s not much you can do with it. I’ve seen this question a few times now so I decided to come up with a solution. Because the

The post Set Default Date/Time Picker Dialog Time appeared first on ServiceNow Guru.

]]>
H

ave you ever wondered how you can change the default time displayed in a Date/Time dialog? In general, the Date/Time dialog is controlled by back-end code so there’s not much you can do with it. I’ve seen this question a few times now so I decided to come up with a solution.

Date Time Picker

Because the Date/Time picker dialog is controlled by back-end code, the only way to change the default time is via client scripting. What I found is that you can run a client script when the dialog comes up and set the hours, minutes, and seconds to whatever you want. The trick is running your client script at the right time. You can’t react to a change or a form submission like you might for regular client scripting scenarios. Instead, you need to react to the click of the calendar icon next to the Date/Time field.

Fortunately, the Prototype library that ships with ServiceNow includes something that does exactly what we need…the Event.observe method. The basic idea behind this method is to wait for a specific event (in this case the ‘onClick’ event from the calendar icon) and then run some code along with that event. I’ve used this method before in an article I wrote about controlling the ordering of client-side code.

Event.observe works by attaching itself to a specific event on a specific element. For the purposes of this solution, we need to find the ‘A’ tag associated with the calendar icon (the element) and check for the ‘click’ event. Then we can run the code to set the time to whatever we want…typically midnight or something similar. Below is a function that does just that. It works for regular forms and for catalog items. You just need to call the function and pass in the name of the Date/Time field or variable like this…

setDatePickerTime('');

…and here’s the ‘setDatePickerTime’ function

function setDatePickerTime(field){
//Attach an event listener to set default time value for date picker
Event.observe($(g_form.getControl(field).id).next('a'), 'click', function() {
setTimeout("$('GwtDateTimePicker_hh').value = '00';$('GwtDateTimePicker_mm').value = '00';$('GwtDateTimePicker_ss').value = '00';",0);
});
}

Here’s an example client script I set up on the Incident form to run onLoad (which will almost always be the case for this script) and attach event listeners to the ‘Opened’ and ‘Closed’ fields so that their time picker would be set to midnignt.

‘Set Date Picker Time’ Client Script
Name: Set Date Picker Time
Table/Catalog Item/Variable Set: Wherever you need it!
Type: OnLoad
Script:

function onLoad() {
//Set the date picker default time to '00' for 'Opened' and 'Closed' fields
setDatePickerTime('opened_at');
setDatePickerTime('closed_at');
}function setDatePickerTime(field){
//Attach an event listener to set default time value for date picker
Event.observe($(g_form.getControl(field).id).next('a'), 'click', function() {
setTimeout("$('GwtDateTimePicker_hh').value = '00';$('GwtDateTimePicker_mm').value = '00';$('GwtDateTimePicker_ss').value = '00';",0);
});
}

The post Set Default Date/Time Picker Dialog Time appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/set-default-datetime-picker-dialog-time/feed/ 39
Calculating Change Dates From Change Tasks https://servicenowguru.com/business-rules-scripting/calculating-change-dates-change-tasks/ Mon, 21 Jun 2010 17:47:01 +0000 https://servicenowguru.wpengine.com/?p=1755 Change management in Service-now includes the use of a parent ‘Change request’ ticket and (usually) the use of multiple ‘Change task’ tickets that can be assigned to separate groups or individuals to perform specific pieces of work. Because these change task tickets should factor into the overall plan for the parent change request, it often

The post Calculating Change Dates From Change Tasks appeared first on ServiceNow Guru.

]]>
Change management in Service-now includes the use of a parent ‘Change request’ ticket and (usually) the use of multiple ‘Change task’ tickets that can be assigned to separate groups or individuals to perform specific pieces of work. Because these change task tickets should factor into the overall plan for the parent change request, it often makes sense to take the expected start and end dates of change tasks into account when setting a planned start and end date for the parent change request. The purpose of this script is to allow you to automate the calculation of the planned start and end dates for the parent change request based on updates made to the child change tasks. Whenever an update is made to the expected start or end dates of a change task, this script will run and evaluate the start and/or end dates of the other change tasks for the same change request. The earliest start date and latest end date from the tasks are then populated as the overall planned start and end dates for the change request.

Sample Title

Since there is no ‘Expected end’ field out-of-box, this script assumes that you’ve created a date/time field named ‘u_expected_end’ on the ‘Change task’ table. ‘Expected start’ and ‘Expected end (u_expected_end)’ on the ‘Change task’ table are the basis for calculating ‘Planned start date (start_date)’ and ‘Planned end date (end_date)’ on the ‘Change request’ table.

Name: Calculate change request dates
Table: Change task (change_task)
When: After Insert/Update
Condition: current.expected_start.changes() || current.u_expected_end.changes()
Script:

calcChangeDates();

function calcChangeDates(){
//updateChange flag so we do not update unless necessary
var updateChange = false;

//Get the parent change to be updated
var chg = new GlideRecord('change_request');
chg.get(current.change_request);

//Query start times
var ts = new GlideRecord('change_task');
ts.addQuery('change_request', current.change_request);
ts.orderBy('expected_start');
ts.query();
while(ts.next()){
if(ts.expected_start && ts.expected_start.getNumericValue() != chg.start_date.dateNumericValue()) {
chg.start_date = ts.expected_start;
updateChange = true;
break;
}
}

//Query end times
var te = new GlideRecord('change_task');
te.addQuery('change_request', current.change_request);
te.orderByDesc('u_expected_end');
te.query();
while(te.next()){
if(te.u_expected_end && te.u_expected_end.getNumericValue() != chg.end_date.dateNumericValue()) {
chg.end_date = te.u_expected_end;
updateChange = true;
break;
}
}

//Update the parent change request if necessary
if(updateChange == true){
chg.update();
}
}

The post Calculating Change Dates From Change Tasks appeared first on ServiceNow Guru.

]]>