Skip to content

Commit 707ebb9

Browse files
Extract & Convert Date in a Text or String to GlideDate
1 parent 10ce92d commit 707ebb9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* This code snippet extracts a date from a string formatted as "20 Nov 2020",
3+
* converts it to GlideDate format, and assigns the date value to the u_last_patch_date field.
4+
*
5+
* While this example is intended for use in a Business Rule (BR), it can be modified
6+
* and utilized in any script within ServiceNow.
7+
*/
8+
(function executeRule(current, previous /*null when async*/) {
9+
10+
// Example value: "kernel-headers-2.6.32-754.35.1.el6.x86_64 20 Nov 2020"
11+
var patchDetails = current.u_patch_description;
12+
13+
// Split the patchDetails string by spaces
14+
var parts = patchDetails.split(' ');
15+
16+
// Find the last three parts which should be day, month, and year
17+
var day = parts[parts.length - 3]; // Example: "20"
18+
var month = parts[parts.length - 2]; // Example: "Nov"
19+
var year = parts[parts.length - 1]; // Example: "2020"
20+
21+
// Construct the formatted date string in yyyy/mm/dd format
22+
var formattedDate = year + '/' + monthToNumber(month) + '/' + (day ? day : '01');
23+
24+
// Function to convert month abbreviation to number (e.g., Jan to 01)
25+
function monthToNumber(monthAbbreviation) {
26+
var months = {
27+
"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06",
28+
"Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"
29+
};
30+
return months[monthAbbreviation] || '01'; // Default to '01' if month is not found
31+
}
32+
33+
// Output the formatted date (for debugging purposes)
34+
gs.info("Formatted Date: " + formattedDate);
35+
36+
// Set the formatted date into the u_last_patch_date field using GlideDate
37+
var gd = new GlideDate();
38+
gd.setValue(formattedDate);
39+
current.u_last_patch_date = gd.getDisplayValue(); // Store the date in GlideDate format
40+
41+
// Update the current record
42+
current.setWorkflow(false);
43+
current.update();
44+
45+
})(current, previous);

0 commit comments

Comments
 (0)