简体   繁体   中英

moment.js convert eastern daylight time to utc?

I have the following function that adds 30 business days to a date. I'm passing in UTC but the output gives me eastern daylight time What can I do to get only UTC out of this function? I've tried moment(tmpDate).utc() but nothing seems to work. Any help would be great, thanks!

function addBusinessDays(date, daysToAdd) {
        var cnt = 0;
        var tmpDate = moment(date);
        while (cnt < daysToAdd) {
            tmpDate = tmpDate.add('days', 1);
            if (tmpDate.weekday() != moment().day("Sunday").weekday() && tmpDate.weekday() != moment().day("Saturday").weekday()) {
                cnt = cnt + 1;
            }
        }

        return tmpDate._d;
    }

    var tmp = addBusinessDays("Tue Apr 04 2017 00:00:00 GMT+0000 (UTC)", 30);

As Charlie pointed out, you are creating a local date. Moment, by default creates local dates.

So a couple of small changes to your function

function addBusinessDays(date, daysToAdd) {
        var cnt = 0;
        var tmpDate = moment.utc(date); // call utc to create a UTC date
        while (cnt < daysToAdd) {
            tmpDate = tmpDate.add('days', 1);
            if (tmpDate.weekday() != moment().day("Sunday").weekday() && tmpDate.weekday() != moment().day("Saturday").weekday()) {
                cnt = cnt + 1;
            }
        }

        return tmpDate.toDate(); // call toDate() to get the JS date out of Moment. Do not use internal private properties.
    }

Now when you call this, you will get a JS date object back. By default it will be local, that's just how they work. However, you can call toISOString on your JS date to get the UTC representation of the date.

var tmp = addBusinessDays("Tue Apr 04 2017 00:00:00 GMT+0000 (UTC)", 30);
console.log(tmp.toISOString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM