Add years to date field in scoped application

Rocky5
Kilo Sage

Hello,

 

I want to add 1 year to the date field (valid_to) in the scoped application and I am using the below script, but looks like 'addYear' and 'getDate' do not work in scoped applications.

 

    var current_date = new GlideDateTime().getDate();
    var gr = new GlideDate();
    gr.addYears(1);
    var fDate = gr.getDate();
    fDate = fDate.getByFormat("MM-dd-YYYY");
    current.valid_to = fDate;
 
this works in global scope but How can I achieve this functionality in scoped app?
 
Thanks,
Rocky.
3 REPLIES 3

DrewW
Mega Sage
Mega Sage

The "addYears" is not supposed to be used so it was not included in scoped apps.  You can use "addYearsLocalTime" or "addYearsUTC".

 

https://developer.servicenow.com/dev.do#!/reference/api/utah/server_legacy/c_GlideDateTimeAPI#r_GDT-...

 

M Ismail
Tera Guru

Hi @Rocky5,

In scoped applications, certain methods are restricted for security and consistency reasons. When dealing with dates and times, ServiceNow often recommends using UTC (Coordinated Universal Time) or local time to ensure consistency across different time zones. In your case, you can use either `addYearsUTC()` or `addYearsLocalTime()` instead of `addYears()` to add a year to a date field.

Here's how you can modify your script to use `addYearsUTC()`:


// Initialize GlideDateTime with the current date and time in UTC
var gdt = new GlideDateTime();

// Add one year to the current date and time in UTC
gdt.addYearsUTC(1);

// Format the GlideDateTime object to a string that matches the field format
// Note: The format should match your instance's date field format, typically 'yyyy-MM-dd'
var formattedDate = gdt.getDisplayValue();

// Set the 'valid_to' field to the formatted date string
current.valid_to = formattedDate;
```

In this script:

- `addYearsUTC(1)` adds one year to the current date and time in UTC.
- `getDisplayValue()` retrieves the string representation of the `GlideDateTime` object based on the user's timezone preference. This ensures that the date displayed is adjusted according to the user's timezone.

MIsmail_0-1711489841870.png


Please hit helpful and accept thsi as a solution if it solved your problem.
Thank you!

With script in scoped application, can we update the date field in the Global scope table?

 

Thanks,

Rocky