javascriptCopy codedefine(['N/format/i18n', 'N/runtime'], function (formatI18n, runtime) {
function getFormattedDate() {
try {
// Get the user's timezone dynamicallyvar userTimezone = runtime.getCurrentUser().getPreference('TIMEZONE');
log.debug("User Timezone", userTimezone); // This will show the user's timezone like "America/New_York"// Get the current datevar currentDate = new Date();
// Format the date using the user's timezone with the i18n modulevar formattedDate = formatI18n.format({
value: currentDate,
type: formatI18n.Type.DATETIME,
timezone: userTimezone // Pass the user's timezone dynamically }); log.debug("Formatted Date in User's Timezone", formattedDate); // This will show the formatted date// Parse it back into a Date object if needed (though it's in UTC)var dateOBJ = new Date(formattedDate);
log.debug("Date Object in User's Timezone", dateOBJ);
return dateOBJ;
} catch (e) {
log.error("Error in getFormattedDate", e.toString());
return null; // Return null if an error occurs
}
}
return {
getFormattedDate: getFormattedDate
};
});
Explanation of the Key Changes:
N/format/i18n Module: Thei18n(Internationalization) module in NetSuite is better for handling date/time formats based on user preferences like timezones, locale, and language.- Dynamic Timezone Handling: We are passing the user’s dynamically fetched timezone into the
formatfunction. This ensures that the date and time returned are formatted according to the user’s specific timezone and preferences. - Date Conversion: The
formatI18n.format()function gives you the date as a string in the user’s timezone. You can still use it as aDateobject for further processing.
Benefits of This Approach:
- Native to NetSuite: Using
N/format/i18nensures compatibility with NetSuite’s timezone handling. - Accurate Timezone Handling: This method takes into account the user’s timezone preferences in NetSuite, which may differ from JavaScript’s native
Intlobject in certain edge cases.
This method is more integrated with NetSuite’s ecosystem and is useful for business logic that needs to respect NetSuite’s user settings.