简体   繁体   中英

Moment.js Local time to UTC for other time zone

I am trying to convert local time ( client machine in India) to UTC time for this particular date for ( 'US/Eastern' ) timezone

tz - 'US/Eastern'
InputDate - 03/12/2017 23:59:59 
Expected output - 03/13/2017 03:59:59
Actual output i am getting - 03/12/2017 18:29

var date1 = moment(inputDate, 'MM/DD/YYYY HH:mm:ss').utc().format('MM/DD/YYYY HH:mm');
var date2 = moment(inputDate, 'MM/DD/YYYY HH:mm:ss').tz(tz).utc().format('MM/DD/YYYY HH:mm'); 

both date1 and date2 returns correct output if i change my local machine time zone to us/newyork timezone but returns wrong if i am in my local timezone of India/Delhi. Where i am missing anything? Thanks in advance.

Try creating your date with moment.tz(date, timezone);

var tz = 'US/Eastern';
var date2 = moment.tz(inputDate, 'MM/DD/YYYY HH:mm:ss', tz).utc().format('MM/DD/YYYY HH:mm')

Try to create the date2 using moment.tz(date, format, timeZone) :

var date2 = moment.tz(inputDate, 'MM/DD/YYYY HH:mm:ss', tz)
                    .utc().format('MM/DD/YYYY HH:mm'); 

 var tz = 'US/Eastern'; var inputDate = '03/12/2017 23:59:59'; var expectedOutput = '03/13/2017 03:59:59'; // Actual output i am getting - 03/12/2017 18:29 var date1 = moment(inputDate, 'MM/DD/YYYY HH:mm:ss').utc().format('MM/DD/YYYY HH:mm'); var date2 = moment.tz(inputDate, 'MM/DD/YYYY HH:mm:ss', tz).utc().format('MM/DD/YYYY HH:mm'); console.log('date1', date1); console.log('date2', date2); console.log('expectedOutput', expectedOutput); 
 <script src="http://momentjs.com/downloads/moment.js"></script> <script src="http://momentjs.com/downloads/moment-timezone-with-data.js"></script> 

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