ANS-0412 · SUITESCRIPT DEVELOPMENT

How to Format a JavaScript Date for NetSuite Date/Time Fields in SuiteScript?

Learn the appropriate methods for converting JavaScript Date objects to NetSuite-compatible Date/Time field formats across SuiteScript versions.

Short answer

For SuiteScript 1.0, use `nlapiDateToString(dateObject, 'datetimetz')`. For modern SuiteScript 2.x, leverage the `N/format` module with `format.format({value: dateObject, type: format.Type.DATETIMETZ})` or directly set a native JavaScript Date object using `record.setValue()`. This ensures proper date and time zone handling in NetSuite Date/Time fields.

Scenario

When working with NetSuite SuiteScript, developers often encounter the need to populate Date/Time fields with values derived from JavaScript Date objects. Directly assigning a JavaScript Date object to a NetSuite Date/Time field without proper formatting can lead to errors or incorrect data storage, particularly concerning time zone considerations. This requires a specific approach to ensure the date and time are correctly interpreted and stored within NetSuite.

Solution

To correctly format a JavaScript Date object for a NetSuite Date/Time field, the method depends on the SuiteScript version being utilized.

For SuiteScript 1.0 environments:

Developers should use the nlapiDateToString function, specifying the datetimetz format. This function converts the JavaScript Date object into a string format that NetSuite's Date/Time fields can properly interpret, including time zone information.

javascript
nlapiDateToString(dateObject, 'datetimetz')

For modern SuiteScript 2.x environments (recommended approach):

The N/format module provides robust capabilities for date and time formatting. The format.format() method should be used, specifying format.Type.DATETIMETZ for fields requiring date, time, and time zone.

javascript
require(['N/format'], function(format) {
    var myDate = new Date(); // Your JavaScript Date object
    var formattedDateString = format.format({
        value: myDate,
        type: format.Type.DATETIMETZ
    });
    // Use formattedDateString to set the field value, e.g., record.setValue({fieldId: 'yourfield', value: formattedDateString});
});

Alternatively, for many record.setValue() operations in SuiteScript 2.x, a native JavaScript Date object can often be passed directly to the field. NetSuite will then handle the conversion based on the field's type and user's time zone settings.

javascript
record.setValue({
    fieldId: 'custrecord_yourdatetimefield',
    value: new Date() // Pass native JavaScript Date object
});

This ensures that the date and time, along with the associated time zone, are accurately stored in NetSuite's Date/Time fields, preventing data discrepancies.

Expert NetSuite Support

Need help with this NetSuite issue?

SuiteScript Development consulting and configuration support

Talk to a consultant