gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Format date into 14-JAN-2024 instead of 14-7-2024 in script in servicenow
- User
Format date into 14-JAN-2024 instead of 14-7-2024 in script in servicenow
- Assistant
Format date into 14-JAN-2024 instead of 14-7-2024 in script in servicenow
Certainly! To format a date in ServiceNow to display as 14-JAN-2024 instead of 14-7-2024, you can use a client-side JavaScript code, often written in Client Scripts or UI Scripts, to achieve this formatting.
Here's an example of how you can do it using a Client Script:
Navigate to Client Scripts:
System Definition > Client Scripts.Create the Client Script:
Table it applies to and setting the Type to onChange or onLoad based on your requirement.function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue == '') {
return;
}
// Get the date value from the form (assuming it's in the 'date_field' field)
var dateVal = g_form.getValue('date_field');
if (dateVal) {
var formattedDate = formatDateString(dateVal);
g_form.setValue('date_field', formattedDate);
}
}
function formatDateString(dateStr) {
// Parse the date string assuming the input is in YYYY-MM-DD format
var parts = dateStr.split('-');
if (parts.length < 3) {
return dateStr; // Return original if the format is not as expected
}
var day = parts[2];
var monthIndex = parseInt(parts[1], 10) - 1; // JavaScript months are 0-based
var year = parts[0];
// Define month names in abbreviated form
var monthNames = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
// Ensure monthIndex is within range
if (monthIndex < 0 || monthIndex >= monthNames.length) {
return dateStr; // Return original if month is out of bounds
}
// Format the date string
return day + '-' + monthNames[monthIndex] + '-' + year;
}
date_field and observing the formatted output.formatDateString takes a date string in YYYY-MM-DD format, splits it into its components, and then constructs a new formatted string in the desired DD-MMM-YYYY format.monthNames array contains the abbreviated month names used in the output format.date_field) contains the date string in YYYY-MM-DD format. You might need to adapt it if your input format is different.Remember to replace 'date_field' with the actual field name you are working with. Additionally, ensure that your script logic aligns with the use case, whether it's loading the form, changing a field value, etc.
Not yet included in a published release.