用Moment Tz格式化日期

时间:2018-07-27 16:48:32

标签: ios datetime ionic-framework fullcalendar momentjs

我正在努力格式化要插入日历的日期。我正在研究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
      }
    );

1 个答案:

答案 0 :(得分: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();
}