【问题标题】:Formatting a date with Moment Tz使用 Moment Tz 格式化日期
【发布时间】:2018-07-27 16:48:32
【问题描述】:

我正在努力格式化要插入日历的日期。我正在开发一个 Ionic 项目,并且正在尝试利用 moment.js 时区。数据分几部分传递到应用程序中。我收到millisecond 日期时间戳、24 小时时间字符串和时区字符串。日期不包含时间。我想要实现的是从这些片段中创建一个日期对象,然后将日期转换为用户的本地时区,以将其添加到他们的设备日历中。

传递给应用的数据示例

The date of the event: August 14, 2018 17:00    
time = 17:00
date = 1534204800
timezone = AEDT

目的地时区基于用户的位置。

    let timeFormatter = new Date();
    timeFormatter.setMilliseconds(date);
    let momentHrMin = moment(timeFormatter.toDateString() + " " + time);

    //WP sever is on GMT get the day, month and yr
    let momentTZDate = momentTz.unix(date);
    momentTZDate.tz('GMT');
    let day = momentTZDate.days();
    let month = momentTZDate.month();
    let yr = momentTZDate.year();

    //set the correct timezone on the ecpoh/unix DATE with momentTz.
    momentTZDate.tz(this.eventDetails.eventDetail.timezoneOffset);

    // Lastly set the date so the timezone conversions are correct
    momentTZDate.set(
      {
        day: day,
        month: month,
        year: yr,
        hour: momentHrMin.hour(),
        minute: momentHrMin.minute(),
        second: 0,
        millisecond: 0
      }
    );

【问题讨论】:

  • 那么出了什么问题?您已经解释了您想要实现的目标,但我们没有描述您当前面临的问题
  • 我面临的问题是我不断输入错误的时区。经过昨天几个小时的文档挖掘,我发现了这个问题。 AEDT 可以代表多个时区(美国东部标准、澳大利亚东部标准等),因此 moment.tz 不接受此值。我只需要使用时刻的时区Australia/Brisbane
  • 你应该把它写成答案而不是评论。将来可能对其他人有用。您还可以吸引投票。
  • @ADyson 伟大的思想都一样,我正在输入一个答案,就像你发送的那样。谢谢你的建议:)

标签: ios datetime ionic-framework fullcalendar momentjs


【解决方案1】:

我找到了我与时区斗争的原因。缩写的 AEDT 不是 Moment.tz 可接受的值。 AEDT 可以代表多个时区。例如,美国东部、澳大利亚东部等......只需将 momentTZDate.tz("AEDT"); 更改为 momentTZDate.tz("Australia/Brisbane"); 即可解决我的问题。下面是我用来解决这个问题的typescript 代码。我不会说它是最好的,但它确实有效。

 private getCalDate(date:number, time: string): Date {

    // create an object in which the hours and minutes can be parse from(do to free text entry on the backend moment handles different inputs)
    let timeFormatter = new Date();
    timeFormatter.setMilliseconds(date);
    let momentHrMin = moment(timeFormatter.toDateString() + " " + time);

    //WP sever is on GMT get the day, month and yr
    let momentTZDate = momentTz.unix(date);
    momentTZDate.tz('GMT');
    let day = momentTZDate.days();
    let month = momentTZDate.month();
    let yr = momentTZDate.year();

    //set the correct timezone on the ecpoh/unix DATE with momentTz.
    momentTZDate.tz("Australia/Brisbane");

    // Lastly set the date so the timezone conversions are correct
    momentTZDate.set(
      {
        day: day,
        month: month,
        year: yr,
        hour: momentHrMin.hour(),
        minute: momentHrMin.minute(),
        second: 0,
        millisecond: 0
      }
    );

    return momentTZDate.toDate();
}

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多