【问题标题】:How to convert windows timezone to moment js timezone如何将windows时区转换为moment js时区
【发布时间】:2018-10-31 19:59:22
【问题描述】:

我有一个下拉菜单可以在 UI 中选择时区。 从 Windows 时区设置下拉列表中获取的下拉数据

如果登录用户选择了某个时区,我必须根据所选时区格式使用 DST 显示所有日期时间字段。

我的表结构是

Typescript ts 代码

import * as moment from 'moment';
import * as momenttimezone from 'moment-timezone';

private ConvertServerTimezoneToClient(dateTime: string, dateFormat: string, timeFormat: string, timezoneFormat: string, isDstzone: string) {
    timeFormat = timeFormat.toString().indexOf('tt') > -1 ? timeFormat.replace('tt', 'a') : timeFormat;
    var convertedTime = '';
    if (timezoneFormat && timezoneFormat != '' && timezoneFormat != "null") {
        if (isDstzone == 'true') {
            momenttimezone.tz.add(''); // need to map
            momenttimezone.tz.link(''); // need to map
            var zoneName = ''; // need to map
            var isDstDate = momenttimezone.tz(new Date(dateTime), zoneName).isDST();
            if (isDstDate) {
                convertedTime = moment(dateTime).zone(timezoneFormat).add(1, 'hours').format(dateFormat + ' ' + timeFormat);
            } else {
                convertedTime = moment(dateTime).zone(timezoneFormat).format(dateFormat + ' ' + timeFormat);
            }
        }
        else {
            convertedTime = moment(dateTime).zone(timezoneFormat).format(dateFormat + ' ' + timeFormat);
        }
    }
    return convertedTime
}

Moment js 有更多的时区格式 https://github.com/moment/moment-timezone/blob/develop/data/packed/latest.json

如何将 windows 时区映射到时刻时区。 UI 基本代码使用 aurelia typescript。需要帮助。

【问题讨论】:

  • 如果您在服务器端代码中运行 .NET,则使用 TimeZoneConverter 可以更好地处理服务器端。
  • 另外,这里显示的代码有几个错误。您不应该尝试手动为 DST 添加一小时。 Moment-timezone 内置了所有这些。此外,除了 tt 到 a 之外,您可能还有其他几种替代方法。

标签: c# timezone momentjs aurelia moment-timezone


【解决方案1】:

没有快速或简单的方法可以做到这一点。 Momentjs 不支持它,也不打算支持它 - 出于同样的原因,您应该真正在服务器上而不是在客户端上执行此操作。如果您需要 .NET 代码中的 Windows 格式的时区,use NodaTime on your server to do this。

如果出于某种原因您仍然坚持在客户端上执行此操作,您可以使用official file for conversion between Windows and IANA timezones。解析该文件,然后使用它来进行映射。

除此之外,我强烈建议使用 UNIX 时间戳而不是字符串。传递一个明确的数字,让每个像样的 DateTime 库都知道如何正确转换,比在任何地方跟踪和正确解析字符串时间戳要容易得多。

【讨论】:

  • 也可以考虑这个答案到类似的topic
猜你喜欢
  • 2020-09-08
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 2018-11-25
  • 2017-09-03
  • 2016-05-21
相关资源
最近更新 更多