【问题标题】:Display time in timezone input without converting to user's timezone在时区输入中显示时间而不转换为用户的时区
【发布时间】:2017-03-14 07:39:11
【问题描述】:

我需要在网页上显示多个时区的时间。该服务以 ISO8601 格式为我提供带有适当偏移量的时间:

"ScheduleTimes": {
    "ScheduledDepartureTime": "2017-03-14T21:55:00.000-07:00",
    "ScheduledArrivalTime": "2017-03-16T06:50:00.000+11:00"
}

现在,当我显示此(出发时间)时间时,我需要将其显示为“14MAR 2155”无论用户在哪里以及浏览器设置的区域设置和时区如何。 p>

标准 Javascript date() 转换为浏览器本地时间。 Moment.js 和它的朋友(例如 react-moment)会做时区转换,但是,我需要知道时区。

例如

<Moment format="HHmm">2017-03-14T21:55:00.000-07:00</Moment>

将其转换为本地时间的小时/分钟。我可以给它一个时区,但我必须获取给定机场代码的时区。我在任何一个给定的显示器中都有几十个,所以我真的不想这样做。 (我只有偏移量,机场,以及大量到达和离开的航班列表,所以我不会一一转换)。

通常在操作控制中心,这对我来说不是问题:默认时区是始终 UTC。这不在 OCC 范围内,适用于预计港口本地时间的不同受众。如果旅程的另一个“终点”位于不同时区的港口,观众不会期望出发/到达时间会转换为他们自己的时区。

除了编写一个专门解析我的日期/时间的自定义类之外,是否有任何解决方案尝试将时间转换为浏览器的时区,并且不需要知道显示时区?

更新

根据下面接受的答案,我创建了一个 React 组件,它允许我在需要不同显示格式的其他地方使用它:

const moment = require('moment');

class LocalTime extends Component {
    formatLocalTime() {
        const t = this.props['value'];
        const f = this.props['format'];
        if (t && f) {
            return moment.utc(t.substring(0, 23)).format(f).toUpperCase();
        } 
        return "";
    }

    render() {
        const formatLocalTime = this.formatLocalTime();
        return (
            <time>{formatLocalTime}</time>
        );
    }
}

所以它的工作原理如下,使用“值”和“格式”属性,我可以在端口本地时间以不同格式显示 STD 和 ETD:

<LocalTime value="2017-03-14T21:55:00.000-07:00" format="DDMMM HH:mm"/>
<LocalTime value="2017-03-14T22:05:00.000-07:00" format="HHmm"/>

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    快速但有点脏:

    const moment = require('moment');
    
    let departure = '2017-03-14T21:55:00.000-07:00';
    let arrival   = '2017-03-16T06:50:00.000+11:00';
    
    function format(t) {
      return moment.utc(t.substring(0, 23)).format('DDMMM HH:mm').toUpperCase();
    }
    
    console.log('Departure:', format(departure));
    console.log('Arrival  :', format(arrival));
    
    // Outputs:
    // Departure: 14MAR 21:55
    // Arrival  : 16MAR 06:50
    

    它从字符串中去除时区偏移量,告诉 Moment 使用余数作为 UTC 时间戳(因此它不会转换为本地),并对其进行格式化。

    【讨论】:

    • 谢谢罗伯特:我看看能不能应用这个解决方案。 Quick and Dirty 有时可以赢得胜利!
    【解决方案2】:

    查看timezonecomplete 库。它似乎不会自动将客户端时区应用于格式方法。

    【讨论】:

    • 谢谢,我会在接下来的几周内看看那个库。
    猜你喜欢
    • 1970-01-01
    • 2014-05-18
    • 2021-12-12
    • 2011-01-18
    • 2015-04-28
    • 2014-01-17
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    相关资源
    最近更新 更多