如何自定义Intl.DateTimeFormat日期?

How to customise Intl.DateTimeFormat date?

我正在尝试使用 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));
  }

这是数据类型问题。您需要为 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 不可用,因此引发错误。

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

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

console.log(numericDate());

在节点中,默认情况下,我们无法像在浏览器中那样访问 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()}`;
  };