我有一个来自我的dynamodb的GMT日期和时间格式,我正在尝试使用momentjs将其转换为EST格式。
2019-06-27 20:00:43.156257
当我将日期放入瞬间时,它会将其转换为+4小时(原本应为-4小时)。
2019-06-28T00:00:43.156Z
我要做的就是这个。
const dbdate = [value-from-db]
const momentdate = moment(dbdate);
我的输出如下:
dbdate:2019-06-27 20:00:43.156257
时刻日期:2019-06-28T00:00:43.156Z
答案 0 :(得分:1)
您必须使用moment.utc()
而不是moment()
:
const dbdate = '2019-06-27 20:00:43.156257';
const momentdate = moment(dbdate);
const utcmomentdate = moment.utc(dbdate);
console.log('local: \n', momentdate);
console.log('utc: \n', utcmomentdate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
答案 1 :(得分:1)
这里有两个问题:
1)Moment正在使用您的本地时区执行时区转换-改为使用moment.utc
2)您的日期不是“官方”支持的格式-尽管实际上它足够宽松以解析您的字符串。理想情况下,应以正确的ISO 8601格式提供它,以避免任何兼容性问题。
您可以尝试以下方法:
const dbdate = '2019-06-27 20:00:43.156257'.split(' ');
const momentdate = moment.utc(dbdate[0] + 'T' + dbdate[1] + 'Z');
alert(momentdate);
这里是fiddle。
希望这会有所帮助!