【问题标题】:How to transform a date according to locale如何根据语言环境转换日期
【发布时间】:2021-03-06 02:43:55
【问题描述】:

我正在尝试根据语言环境更改日期格式。目前我的要求只有两个语言环境:

  1. zh-CN(英语)
  2. de-De(德语)

我尝试了一些东西,但我得到了这个错误:

错误错误:无法将“无效日期”转换为日期 角 2 转换 ... ...

这是模板:

<button (click)="apply()"></button>

这是我的逻辑:

  primaryStartDateLabel: string;
  primaryEndDateLabel: string;
  secondaryStartDateLabel: string;
  secondaryEndDateLabel: string;

  parentLocale = "en-US";

  apply() {
    const primaryDateLabels = "01-01-2021,03-05-2021";
    const secondaryDateLabels = "01-01-2020,03-05-20210";
    this.extractDateLabels(primaryDateLabels, secondaryDateLabels);
  }

  extractDateLabels(primaryDateLabels, secondaryDateLabels) {
    const primaryLabels = primaryDateLabels.split(",");
    const secondaryLabels = secondaryDateLabels.split(",");
    console.log("after split ", primaryLabels);
    console.log("after split ", secondaryLabels);
    this.primaryStartDateLabel = this.myFormatDate(primaryLabels[0]);
    this.primaryStartDateLabel = this.transform(
      this.primaryStartDateLabel,
      this.parentLocale
    );
    this.primaryEndDateLabel = this.myFormatDate(primaryLabels[1]);
    this.primaryEndDateLabel = this.transform(
      this.primaryEndDateLabel,
      this.parentLocale
    );
    this.secondaryStartDateLabel = this.myFormatDate(secondaryLabels[0]);
    this.secondaryStartDateLabel = this.transform(
      this.secondaryStartDateLabel,
      this.parentLocale
    );
    this.secondaryEndDateLabel = this.myFormatDate(secondaryLabels[1]);
    this.secondaryEndDateLabel = this.transform(
      this.secondaryEndDateLabel,
      this.parentLocale
    );
  }

  transform(value: string, locale: string) {
    console.log("looking_1 ", value, locale);
    let format;
    if (locale === "en-US") {
      format = "MM-dd-y";
    } else {
      format = "mediumDate";
    }
    console.log("looking_1 ", format);
    return formatDate(value, format, locale);
  }

  myFormatDate(value: string) {
    const stringValue = new Date(
      moment(value, "MM-DD-YYYY").format("YYYY-MM-DD")
    );
    return stringValue.toDateString();
  }

当区域设置为 en-Us 时,日期应为:“03-23-2021”

但是当语言环境是 de-De 或其他时,日期应该是:“03.23.2021”

这是一个stackblitz(与时刻相关的错误)。

请帮助我实现我的目标。

P.S:由于某些限制,我不能从角度使用日期管道。我必须自己创建一些可定制的东西。

【问题讨论】:

    标签: angular


    【解决方案1】:

    简化时刻导入。 import moment from "moment";

    不需要额外的变量赋值moment = _moment;

    最后拨打moment(value, "MM-DD-YYYY").format("YYYY-MM-DD")

    编辑: 导入时刻语言环境import 'moment/min/locales';

    parentLocale 的值更改为usde,看看它的神奇之处。

    stackblitz的最终工作结果。

    【讨论】:

    • 你解决了瞬间问题兄弟。谢谢你,但我需要更改语言环境。也请帮助我。
    • 已实现区域设置。请重新检查。
    • 如果有时间请指出我的错误
    • 欢迎。我其实不知道你的明确要求。因此,更多细节可能有助于理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多