Set Date and Time value of a custom field based on User’s preferred Time Zone

To set the date and time value of a custom field based on User’s preferred Time Zone, we can use the sample script below.
Script below captures the current date and time when the Sales Order record is created based on the User’s preferred Time Zone.

For the sample, the User’s preferred Time Zone is ‘Asia/Manila’ or (GMT+08:00) Manila.

function beforeSubmit(type) {
 nlapiLogExecution(‘DEBUG’, ‘Before Submit’, ‘type = ‘ + type); var d = new Date();
 var yyyy = d.getFullYear().toString();
 var mm = (d.getMonth() + 1).toString();
 var dd = d.getDate().toString();
 var time = formatAMPM(d);
 var val = (mm[1] ? mm : mm[0]) + ‘/’ + (dd[1] ? dd : dd[0]) + ‘/’ + yyyy + ” ” + time;

 var conf = nlapiLoadConfiguration(‘userpreferences’);
 var tz = conf.getFieldValue(‘TIMEZONE’);

 // The current date and time captured within the server is set to PST that is why we need to set it first to “America/Los_Angeles”
 // “custbody_orig_date” is the internal id of the custom field with field type of “Date/Time”
 
 nlapiSetDateTimeValue(‘custbody_orig_date’, val, ‘America/Los_Angeles’);

 // We then set the Time Zone to the User’s preferred
 nlapiSetDateTimeValue(‘custbody_orig_date’, nlapiGetDateTimeValue(‘custbody_orig_date’), tz);
}



function beforeSubmit(context) { log.debug({ title: ‘Before Submit’, details: ‘type = ‘ + context.type }); var currentDate = new Date(); var formattedDate = formatDate(currentDate) + ‘ ‘ + formatAMPM(currentDate); var userPreferences = config.load({ type: config.Type.USER_PREFERENCES }); var userTimeZone = userPreferences.getValue({ fieldId: ‘TIMEZONE’ }); // Set the current date and time in the ‘America/Los_Angeles’ timezone initially record.setValue({ fieldId: ‘custbody_orig_date’, value: formatDateInTimeZone(formattedDate, ‘America/Los_Angeles’), type: context.newRecord.type }); // Set the timezone to the user’s preferred timezone record.setValue({ fieldId: ‘custbody_orig_date’, value: formatDateInTimeZone(currentDate, userTimeZone), type: context.newRecord.type }); } function formatDate(date) { return format.format({ value: date, type: format.Type.DATE }); } function formatAMPM(date) { return format.format({ value: date, type: format.Type.TIMEOFDAY }); } function formatDateInTimeZone(date, timeZone) { return timezone.format({ value: date, type: timezone.Type.DATETIME, timezone: timeZone }); }

Leave a comment

Your email address will not be published. Required fields are marked *