【问题标题】:How to customise Intl.DateTimeFormat date?如何自定义 Intl.DateTimeFormat 日期?
【发布时间】:2019-12-31 05:57:06
【问题描述】:

我正在尝试使用 Intl.DateTimeFormat 并传递语言环境和 dateStyle、timeStyle 选项来更新我的 angular 6 应用程序中的日期。我可以在浏览器控制台中尝试获取自定义日期,但是一旦我尝试将其集成到我的应用程序中,它就会引发编译错误:Type '{ dateStyle: string; timeStyle: string; }' has no properties in common with type 'DateTimeFormatOptions'.

    transformDate() {
    const options = { dateStyle: "full", timeStyle: "medium" };
    console.log(new Intl.DateTimeFormat('en-US',options).format(this.date));
  }

【问题讨论】:

    标签: javascript html angular datetime internationalization


    【解决方案1】:

    这是数据类型问题。您需要为 options 指定数据类型。

    你可以试试——

     const options: any = { dateStyle: "full", timeStyle: "medium" };
    

    基本上 Intl.DateTimeFormat 接受 DateTimeFormatOptions 类型的选项, 它具有属性

    interface DateTimeFormatOptions {
            localeMatcher?: string;
            weekday?: string;
            era?: string;
            year?: string;
            month?: string;
            day?: string;
            hour?: string;
            minute?: string;
            second?: string;
            timeZoneName?: string;
            formatMatcher?: string;
            hour12?: boolean;
            timeZone?: string;
        }
    

    由于 dateStyle 和 timeStyle 不可用,因此抛出错误。

    【讨论】:

      【解决方案2】:

      编辑:实际上,我似乎错误地回答了错误的问题,如果我需要将其作为en-US 的默认格式,请使用技巧;它不会让你什么都不放,但由于某种原因,它会允许一个空数组。如果你真的想要它简短,请输入任何一位数字,这也将被假定为“en-US”

      function numericDate() {
        var ops = {year: 'numeric'};
        ops.month = ops.day = '2-digit';
        return new Date().toLocaleDateString([], ops);
      }
      
      console.log(numericDate());

      【讨论】:

      • 感谢您的努力!但是,我打算在这里实现的是根据不同国家/地区文化中的格式来格式化特定日期,例如美国的 MM/DD/YYYY 和德国的 DD.MM.YYYY。
      • 啊,忘记那部分了,现在编辑。我有一个巧妙的技巧,适用于所有浏览器的最新版本,不像这个。,嗯,它仍然不是这个的合适答案;我的目标是另一个(stackoverflow.com/questions/46228846/…),但不知何故搞混了。
      • 顺便说一句,您可以使用DateTimeFormat('default') 而不是[]
      【解决方案3】:

      在节点中,默认情况下,我们无法像在浏览器中那样访问 dateStyle 属性。

      我使用如下配置:

      const TimeFormat = () => {
          const options = {
            day: "2-digit",
            month: "2-digit",
            year: "numeric",
            hour: "numeric",
            minute: "numeric",
            second: "numeric",
            fractionalSecondDigits: 3,
            hour12: false,
            timeZone: "UTC",
          };
          return `${Intl.DateTimeFormat("pt-BR", options).format(
            data
          )}.${data.getMilliseconds()}`;
        };
      

      【讨论】:

        猜你喜欢
        • 2017-09-13
        • 2021-02-10
        • 2014-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多