Search code examples
javascriptparse-platformtimezonemomentjsparse-cloud-code

Javascript: moment().to() doesn't seem to work with moment().utcOffset() on Parse


I'm having trouble getting moment().to() and moment().utcOffset() place nicely together on Parse cloud code.

I'm running this as cloud code on Parse.com which is always in UTC. The (simplified) code is

function cafeOpenState(cafe, utcOffset) {
    var returnString;

    var now = moment();
    now.utcOffset(utcOffset);
    var dayStr = now.format('ddd');

    // Get appropriate open and closing times
    var openTime = Number(cafe.get('OpenTime')); // stored as 3-4 digit integer e.g. 830
    var closeTime = Number(cafe.get('CloseTime')); // stored as 3-4 digit integer e.g. 2130

    // Figure out what time it is now, in 0-2400 format
    var timeNowStr = now.format('Hmm'); // need this later
    var timeNow = Number(timeNowStr);

    // Find out where it is currently in the time range
    if (openTime == 0 && closeTime == 0) {
        returnString = 'Closed today';
    } else if (timeNow < openTime) {
        var openTimeMoment = moment(openTime, 'Hmm');
        var opensIn = now.to(openTimeMoment);
        var opensInStr = openTimeMoment.format('H:mm');
        returnString = 'Not yet open, opens ' + opensIn + ' at ' + opensInStr;
    } else if (timeNow > openTime && timeNow < closeTime) {
        var closeTimeMoment = moment(closeTime, 'Hmm');
        var closesIn = now.to(closeTimeMoment);
        var closesInStr = closeTimeMoment.format('H:mm');
        returnString = 'Currently open , closes ' + closesIn + ' at ' + closesInStr;
    } else if (timeNow > closeTime) {
        returnString = 'Closed for today';
    } else {
        returnString = 'error';
    }

    // Return a human readable string
    return returnString;
}

The problem is that even though 'now', 'openTimeMoment' and 'closeTimeMoment' show the correct, UTC-adjusted times, the 'to' function seems to ignore it for 'now'. For example, I get output like (when the time is 15:00, and I've checked that now is correct) 'Currently open, closes in 10 hours at 17:00'.

10 hours is correct if you don't include the utc adjustment of 8 hours. But it obviously should be 2 hours.

Cannot reproduce this in a JSFiddle - works fine. I'm using the same version of moment.js on Parse as on a fiddle. Any ideas?


Solution

  • I solved it - I was using utcOffset incorrectly.

    I managed to correct my function by removing now.utcOffset(utcOffset); and replacing it with now.add(utcOffset - now.utcOffset(), 'minutes');

    If there's a better answer, I'd like to see it...