Search code examples
javascriptmomentjsutc

Convert string date to utc


I have a string date and utcoffset

var date = '06/30/2016';
var utcOffset = -7.0;

I need a Javascript function to convert string date to utc using utcoffset

I tried the following way it works only on chrome but doesn't work in IE/11/edge and FF.

 var date = '06/30/2016';
 var utcOffset = -7.0;
 var startDate = moment(date).toDate();        
 var offsetDate = moment(startDate + offset).toDate();

Is there any other way I could achieve this across all the browsers.

I also tried the below approach but it doesn't work

var date = '06/30/2016';
 var utcOffset = -7.0;
 var d = moment(date).toDate();  
d.setTime( d.getTime() + offset*60*1000 );

Solution

  • Please try the following function:

    function dateToUTC(date, offset) {
        var tzDate = moment(date).utcOffset(offset);
        var utcDate = new Date(date+tzDate.format('ZZ'));
        if(isNaN( utcDate.getTime() ) ) {
            return moment(date+tzDate.format('Z'))
        }
        return moment(utcDate);
    }
    

    Usage:

    var date = '06/30/2016';
    var utcOffset = -7.0;
    
    dateToUTC(date, utcOffset); // Thu Jun 30 2016 07:00:00 GMT+0000
    

    Demo: https://jsfiddle.net/3v9cd6uf/