2017-09-22 43 views
0

我的时刻对象不会转换时区。我试图将日期和时间对象转换为UTC,但它只是返回原始日期/时间而不更改。有谁知道为什么会发生这种情况?它看起来可能会假设原始时间为UTC,即使它不符合_d?瞬时时区转换不起作用

momentPre = moment(post.date + " " + post.time + "00", "YYYY-M-D HH:mm:ss") 
momentAft = momentPre.toISOString() 
momentParse = moment.tz(momentAft, 'America/Denver') 
post.utcDate = momentParse.clone().tz("UTC")._i.substring(0,10) 

momentParse对象输出(_isUTC返回true,即使它不是我已经迫使这个假之前测试和犯规解决问题。):

{ [Number: 1506010200000] 
    _isAMomentObject: true, 
    _i: '2017-09-21T16:10:00.000Z', 
    _f: 'YYYY-MM-DDTHH:mm:ss.SSSSZ', 
    _tzm: 0, 
    _isUTC: true, 
    _pf: 
    { empty: false, 
    unusedTokens: [], 
    unusedInput: [], 
    overflow: -1, 
    charsLeftOver: 0, 
    nullInput: false, 
    invalidMonth: null, 
    invalidFormat: false, 
    userInvalidated: false, 
    iso: true }, 
    _locale: Locale { ordinal: [Function], _abbr: 'en' }, 
    _a: [ 2017, 8, 21, 16, 10, 0, 0 ], 
    _d: Thu Sep 21 2017 04:10:00 GMT-0600 (MDT), 
    _z: 
    { name: 'America/Denver', 
    abbrs 
    ... 

输出momentParse.clone() .tz(“UTC”)

{ [Number: 1506010200000] 
    _isAMomentObject: true, 
    _i: '2017-09-21T16:10:00.000Z', 
    _f: 'YYYY-MM-DDTHH:mm:ss.SSSSZ', 
    _tzm: 0, 
    _isUTC: true, 
    _offset: 0, 
    _pf: 
    { empty: false, 
    unusedTokens: [], 
    unusedInput: [], 
    overflow: -1, 
    charsLeftOver: 0, 
    nullInput: false, 
    invalidMonth: null, 
    invalidFormat: false, 
    userInvalidated: false, 
    iso: true }, 
    _locale: Locale { ordinal: [Function], _abbr: 'en' }, 
    _z: 
    { name: 'UTC', 
    abbrs: [ 'UTC' ], 
    untils: [ Infinity ], 
    offsets: [ 0 ] }, 
    _a: [ 2017, 8, 21, 16, 10, 0, 0 ], 
    _d: Thu Sep 21 2017 10:10:00 GMT-0600 (MDT) } 
+0

您是否添加了当前时区的js文件 – Thusitha

+0

是的,我正在使用mrt:moment-timezone软件包。 – Silicabello

+0

我不完全确定你的问题究竟是你想要在用例方面达到什么目的,你为什么需要这样做。当你保存Meteor Collection中的任何字段时,它默认保存为UTC。客户端感觉不同。客户根据他们的时区将能够正确读取日期。那么,为什么你需要时区转换?如果你真的需要它,请你解释为什么在这个问题上? –

回答

0

它的工作,你只是得到日期错误的方式。

而不是momentObj._i.substring(0,10)您应该使用momentObj.format()方法。

const now = moment() 
now.tz('UTC').format() 
# 2017-09-22T04:39:58Z 
now.clone().tz('Europe/Kiev').format() 
# 2017-09-22T07:39:58+03:00 
now.clone().tz('America/Denver').format() 
# 2017-09-21T22:39:58-06:00 

这里是.format() documentation

新增:仅使用,如果你想离开now不变.clone()是必要的,否则你可以做now.tz(...).format(...)