Timezone issue for Start Date in map/reduce || RESOLVED THE ISSUE

PHOTO EMBED

Thu Jan 19 2023 08:40:20 GMT+0000 (Coordinated Universal Time)

Saved by @mdfaizi #javascript

/**
     * @author Anirban Gupta (Huron)
     * @NApiVersion 2.1
     * @NScriptType UserEventScript
     * @NModuleScope SameAccount
     * @NAmdConfig /SuiteScripts/Library/requireConfig.json
     */
/**
     * Module Description
     * Script to adjust Date and Time to be entered from the User's end if the User's Timezone and Server's Timezone does not match.
     *
     *  Version   Date           Author              Comments
     *  1.0       18 Jan 2023    Anirban Gupta       Script Created.
     *
 */

define(['N/runtime', 'N/format', 'N/config', 'moment', 'moment-timezone'], function (runtime, format, config, moment, momentTz) {
    /**
     * Function definition to be triggered before record is submitted.
     *
     * @param {Object} context - Context
     * @Since 2015.2
     */
    function beforeSubmit(context) {
        log.audit('UE Type', context.type);
        log.audit('Execution Context', runtime.executionContext);
        let userObj = runtime.getCurrentUser();
        log.audit('User', 'User Internal ID:' + userObj.id);

        if (isSupportedUserEventType(context) && isSupportedContext()) {
            try {
                let userTimezone = userObj.getPreference({
                    name: 'timezone'
                });
                log.debug('Timezone', 'User preference for timezone: ' + userTimezone);

                let serverConfigurationRecord = config.load({
                    type: config.Type.COMPANY_INFORMATION
                });

                /* Fetching Server Timezone */
                let serverTimeZone = serverConfigurationRecord.getValue('timezone');
                log.debug('TimeZone', 'Server timezone: ' + serverTimeZone);

                /* If User's Timezone is not the same as the server's Timezone - we are manipulating the Date/Time to be set */
                if (userTimezone !== serverTimeZone) {
                    let startdate = context.newRecord.getValue('startdate');
                    let originalTime = format.parse({
                        value: startdate,
                        type: format.Type.DATETIME,
                        timezone: userTimezone
                    });
                    log.debug('Original Time', 'Original Time: ' + originalTime);
                    let originalDateInMomentFormat = parseInt(originalTime.getFullYear()) + '-' + (originalTime.getMonth() + 1) + '-' + parseInt(originalTime.getDate());

                    /* Calculating difference between Server's Timezone and User's Timezone */
                    let timeDifferenceInMinutes = momentTz(originalDateInMomentFormat).tz(userTimezone).utcOffset() - momentTz(originalDateInMomentFormat).tz(serverTimeZone).utcOffset();

                    /* Sometimes an entire day's minutes (1440) is added to the difference when we are calculating offset between a non-DST timezone and a DST timezone on the DST shift day, hence we are recalculating to get the correct difference */
                    while (timeDifferenceInMinutes > 1440) {
                        timeDifferenceInMinutes -= 1440;
                    }
                    while (timeDifferenceInMinutes < -1440) {
                        timeDifferenceInMinutes += 1440;
                    }

                    /* Adding the difference between the Server's Timezone and User's Timezone to the Date/Time set by the User */
                    let adjustedUserDateTime = new Date(momentTz(originalDateInMomentFormat).add(timeDifferenceInMinutes, 'minutes').tz(userTimezone).toISOString());

                    /* Preparing Date */
                    let adjustedUserDate = (adjustedUserDateTime.getMonth() + 1) + '/' + parseInt(adjustedUserDateTime.getDate()) + '/' + parseInt(adjustedUserDateTime.getFullYear());
                    let formattedAdjustedDate = format.parse({ value: adjustedUserDate, type: format.Type.DATE });
                    log.debug('Adjusted User Date', adjustedUserDate);

                    /* Preparing Time */
                    let adjustedUserTime = moment(adjustedUserDateTime).format("hh:mm a");
                    log.debug('Adjusted User Time', adjustedUserTime);

                    context.newRecord.setValue('startdate', formattedAdjustedDate);
                    context.newRecord.setText('starttime', adjustedUserTime);

                    log.audit('Adjusted Date', 'Adjusted Date And Time is:' + adjustedUserDateTime);
                }
            } catch (error) {
                log.debug("Error", error.name + ' ' + error.message + ' ' + error.stack);
            }
        }
    }

    let isSupportedUserEventType = (context) => {
        let UserEventType = context.UserEventType;
        return [UserEventType.CREATE, UserEventType.EDIT, UserEventType.XEDIT].indexOf(context.type) > -1;
    };

    // Does not support Webstore and RESTlet
    let isSupportedContext = () => {
        let ContextType = runtime.ContextType;

        return [
            ContextType.CLIENT,
            ContextType.CSV_IMPORT,
            ContextType.USEREVENT,
            ContextType.USER_INTERFACE,
            ContextType.WORKFLOW].indexOf(runtime.executionContext) > -1;
    };

    return {
        beforeSubmit: beforeSubmit
    };
});
content_copyCOPY