【问题标题】:convert set of numbers to date in angular 10将一组数字转换为角度 10 中的日期
【发布时间】:2022-01-26 11:20:00
【问题描述】:

我有一个具有这种格式的字符串

20220125

yyyymmdd

但我需要将其转换为以下格式

2021-01-25

有没有办法用 angular 10 做到这一点?

【问题讨论】:

标签: angular date datetime


【解决方案1】:

对于有效的 ISO 日期,其格式应为:“2022-01-25”。这是一个给你的例子,它当然可以变得更可靠。但对于演示目的,它应该可以工作。

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  dateVal: Date;
  dateString = '20220125'
  constructor() {
    this.convertStringToDate(this.dateString)
  }

  convertStringToDate(dateString: string) {
    if (dateString.length == 8) {
      let formatedString = dateString.slice(0, 4) + '-' + dateString.slice(4, 6) + '-' + dateString.slice(6, 8);
      const dateObj = new Date(formatedString);
      console.log(formatedString);
      console.log(dateObj);
      this.dateVal = dateObj;

    }
  }
}

2022-01-25

2022-01-25T00:00:00.000Z

这是一个工作演示:https://stackblitz.com/edit/date-pipe-example-k4zewb?file=app%2Fapp.component.ts

【讨论】:

    【解决方案2】:

    您可以直接使用 Javascript 并使用正则表达式模式替换字符串。

    const date = "20220125";
    const re = date.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");
    console.log(re)
    
    > "2022-01-25"
    

    【讨论】:

      【解决方案3】:

      使用“时刻”库的最佳方式

      【讨论】:

        猜你喜欢
        • 2020-11-29
        • 1970-01-01
        • 2015-07-09
        • 2022-06-10
        • 1970-01-01
        • 2018-02-05
        • 2021-09-02
        • 2019-07-29
        • 2023-01-20
        相关资源
        最近更新 更多