How to handle Date objects without been affected by timezone

Posted By Manisha Kirodiwal | 22-Jan-2018

Some places we need to make the consistency of date and time which we have entered or select from the calendar without getting affected by local timezone.
For example, if we are entering a date or time from India ( India is my local timezone ) and we want to display the same date without affecting it by the timezone then we can use the following code where we are sending the timestamp to the backend and be fetching the same time stamp from the backend.
 
In the following example, we are using Moment Timezone Js for converting dates between time zones.
Here we are using two functions first one is returning timestamp by adding the difference of minutes in both timezones which we will send to the backend then when backend returns the same timestamp then we will pass that to the second function. The second function returns the date object by converting it to the respective timezone.


Returns Timestamp: 

 

/**
    * Returns timestamp of passed date
    * by adding, difference of your localTimeZoneUtcOffset and organizationTimeZoneUtcOffset in date
    * @param date date object
    */

    static getTimeStamp(date?: Date): number {
        let result;
        let timeStamp;
        if (this._timeZone) {
            const currentMoment = moment();
            const localOffset = currentMoment.utcOffset();
            const convertedMoment = moment().tz(this._timeZone);
            const timeZoneOffset = convertedMoment.utcOffset();
            const diffInMinutes = localOffset - timeZoneOffset;
            if (date) {
                result = addMinutes(date, diffInMinutes);
            } else {
                result = addMinutes(new Date(), diffInMinutes);
            }
            timeStamp = result.getTime();
        } else {
            if (date) {
                timeStamp = date.getTime();
            } else {
                timeStamp = new Date().getTime();
            }
        }
        return timeStamp;
    }

 


Returns Date Object:

    /**
     * Returns Date Object after converting your passed timestamp into the organization's timezone
     * @param timeStamp Timestamp
     * @param dateFormat Format of returned date object
     */
    static getDateUsingTimeStamp(timeStamp: number, dateFormat?: string): Date {
        const defaultFormat = 'MM/DD/YYYY HH:mm:ss';
        let date = '';
        if (this.timezone) {
            if (dateFormat) {
                date = moment(timeStamp).tz(this._timeZone).format(dateFormat);
            } else {
                date = moment(timeStamp).tz(this._timeZone).format(defaultFormat);
            }
        } else {
            date = format(timeStamp, 'MM/DD/YYYY HH:mm:ss');
        }
        const dateObj = new Date(date);
        return dateObj;
    }

 

Request for Proposal

Recaptcha is required.

Sending message..