We've updated the ServiceNow Community Code of Conduct, adding guidelines around AI usage, professionalism, and content violations. Read more

how to convert year to date for custom table during Data Load

sony8
Tera Contributor

Hi ,

 

I got stuck in the following validation for one my data source load for one of our tables.

 

Need to load data for a table which we are receiving data in the below format

we are receiving instead of date as year as below

date : 01/01/2022 

year:2022

 

I Have created a new field called Date and need to set year to Date as above.

 

Can someone help me how to achieve below issue?

 

 

3 REPLIES 3

Amit Gujarathi
Giga Sage

HI @sony8 ,
I trust you are doing great.
Please find the sample code for the same.

(function executeRule(current, previous /*null when async*/) {
    // Check if the year field is not empty
    if (current.year) {
        // Create a new Date object for January 1st of the given year
        var date = new Date(current.year, 0, 1); // JavaScript months are 0-indexed, so 0 represents January

        // Format the date to ServiceNow's standard format
        var formattedDate = formatDate(date);

        // Set the formatted date to the 'Date' field
        current.date = formattedDate;
    }

    function formatDate(date) {
        // Formats the date to 'yyyy-mm-dd' format
        return new GlideDateTime(date).getByFormat('yyyy-MM-dd');
    }

})(current, previous);

Was this answer helpful?


Please consider marking it correct or helpful.


Your feedback helps us improve!


Thank you!


Regards,


Amit Gujrathi



Sandeep Rajput
Tera Patron

@sony8 Please use the following script.

 

var stringYear = '2001';//assign value from the year variable
stringYear = '01/01/'+stringYear
var someDate = new GlideDate();
someDate.setDisplayValue(stringYear);
gs.info(someDate.getDisplayValue());

Ashir Waheed
Kilo Sage

Hi @sony8 

 

To format date in transform map use the below steps:

1. Open your transform map and click on the date field you mapped.

AshirWaheed_1-1700766275386.png

2. Check the Use Source Script field and enter the Date format as required.

3. Source.u_custom_date is the field on excel and target.u_custom_date is the field on the table.

4. Write the script as mentioned according to your fields.

AshirWaheed_2-1700766422993.png

 
answer = (function transformEntry(source) {
gs.log(source.u_custom_date, "Ashir");
var year = source.u_custom_date;
var month = "01";
var day = "01";
var finalDate = day + '/' + month + '/' + year;
var gdt = new GlideDateTime(finalDate);
target.u_custom_date = gdt;
})(source);
 

5. Save the record and Run the transform map again.

6. You will be able to the result as below

AshirWaheed_3-1700766616170.png

 

Hopefully this may resolves your issue.

 

Regards,

Ashir Waheed