Reputation: 1280
I am using moment timezone converter for timezone date conversions on my website. By default I am showing date and time in IST. I have a button which converts the given time in user's timezone. This button action calls moment js and does the conversion. Upto here I have no problem. The problem arises when I revert the time back to IST and the conversion never happens. Is there anything that I am missing here ?
<script type="text/javascript">
var userTzName = 'America/New_York';
var dateFormat = 'YYYY-MM-DD HH:mm:ss';
var timeStr = '2015-01-17 21:00:00';
var convertedStr = moment(timeStr).tz(userTzName).format(dateFormat);
console.log(convertedStr);
//after sometime or on user action(button click)
userTzName = 'Asia/Kolkata';
timeStr = '2015-01-17 10:30:00'; //this is the converted string from original coversion
var convertedStr1 = moment(timeStr).tz(userTzName).format(dateFormat);
console.log(convertedStr1);
</script>
Upvotes: 0
Views: 3121
Reputation: 1280
sorry this was not a bug. I was wrongly using the library. All I did was to pass the ISO date string to my moment function and it worked like a charm. My previous implementation did not work because when I converted my datetime string the first time moment always thought that the converted datetime was in IST. So all I had to do was communicate to moment that my timezone was different when the second conversion happens and that I was able to achieve through ISO date string. Here is the code:
<script type="text/javascript">
var userTzName = 'America/New_York';
var dateFormat = 'YYYY-MM-DD HH:mm:ss';
var timeStr = '2015-01-17T21:00:00+05:30';//this is a ISO date string
var convertedStr = moment(timeStr).tz(userTzName).format(dateFormat);
console.log(convertedStr);
</script>
Upvotes: 1