Helen Araya
Helen Araya

Reputation: 1946

Get The date time from UTC using offset minutes

The user have offset minutes from utc which is 360.000009361667 and now I want to have the current user date time using moment

function getUserTimeZoneDateTime() {

    var currentUtcDateTime = moment.utc().toDate();
    var mod_start = new Date(currentUtcDateTime.setMinutes(GlobalValues.OffsetMinutesFromUTC - currentUtcDateTime.getTimezoneOffset()));
    var currentUserDateTime= moment(mod_start).format('MM/DD/YYYY h:mm A');

    return currentUserDateTime;
};

But this gives me the correct date but the time is not correct it only gives me 5 PM, 6PM on the time portion the minutes are rounded to 0.

But What I want is the current date and time with minutes and seconds.

Upvotes: 1

Views: 330

Answers (2)

shukshin.ivan
shukshin.ivan

Reputation: 11340

You forgot to add minutes to setMinutes:

function getUserTimeZoneDateTime() {

    var currentUtcDateTime = moment.utc().toDate();
    var mod_start = new Date(currentUtcDateTime.setMinutes(currentUtcDateTime.getMinutes() + GlobalValues.OffsetMinutesFromUTC - currentUtcDateTime.getTimezoneOffset()));
    var currentUserDateTime= moment(mod_start).format('MM/DD/YYYY h:mm A');

    return currentUserDateTime;
};

The difference that you use wrong in parenthesis is always an integer number of hours.

You can also use easier way: moment(obj).utcOffset(OffsetMinutesFromUTC); to set offset:

function getUserTimeZoneDateTime() {
    var currentUtcDateTime = moment.utc().toDate();
    return moment(currentUtcDateTime).utcOffset(GlobalValues.OffsetMinutesFromUTC - currentUtcDateTime.getTimezoneOffset()).format('MM/DD/YYYY h:mm A');
};

Upvotes: 1

Mad Alex
Mad Alex

Reputation: 1

var now = new Date().getTime();

This gets the time and stores it in the variable, here called now. It should get the time wherever the user is. Hope this helps!

Upvotes: 0

Related Questions