How to set timezone with moment?

2019-03-04 16:40发布

问题:

i am using moment for getting server time .

moment.tz.setDefault("Asia/Kolkata");

var now = new Date();
var _p_date = moment.tz(now, zone).format(); 

time when inserting _p_date = 2016-01-05T18:32:00+05:30 But in database date variable is type of DATETIME. and time is saved as 2016-01-05 18:32:00. and after that when i comparing with this to get time_ago funcionality. providing me wrong estimation.

using time ago = moment("2016-01-05T18:32:00.000Z").fromNow(); // is showing In 5 hours

回答1:

Since your initial timezone is lost you have to create moment.tz object with selected timezone. Try this plunker

var date = moment.tz(moment("2016-01-05T18:32:00.000Z", "YYYY-MM-DDTHH:mm")
    .format('YYYY-MM-DD HH:mm'), 'Asia/Kolkata');


console.log(date.fromNow());