Shashi
Shashi

Reputation: 1182

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 );

Upvotes: 0

Views: 870

Answers (2)

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

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/

Upvotes: 1

Saurabh Chaturvedi
Saurabh Chaturvedi

Reputation: 2156

Try this below code , it should work . It works well for me on all the browsers .

    var d =new Date(modifieddate);
                var _userOffset =d.getTimezoneOffset()*60000; 
                d = new Date(d.getTime()+_userOffset);

You can put your own offset value instead of calculating . Let me know if that helped you :)

Upvotes: 0

Related Questions