代码之家  ›  专栏  ›  技术社区  ›  VirtualProdigy

用矩Tz格式化日期

  •  0
  • VirtualProdigy  · 技术社区  · 6 年前

    我正在努力格式化日期以插入日历。我在做一个离子项目,我试图利用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 回复  |  直到 6 年前
        1
  •  1
  •   VirtualProdigy    6 年前

    我找到了我与时区斗争的原因。缩写的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();
    }