如何将动态日期转换为特定格式

时间:2018-09-04 10:53:14

标签: html angular typescript

我尝试将字符串日期转换为特定格式, (即) 1995-09-22至1995年9月22日

let dat = new Date();
      var options = { day: "numeric", month: "long", year: "numeric" };
      let local = dat.toLocaleDateString("en-US", options);
      console.log(local);


// With dynamic date string(Not working)
let dat = "1995-09-22"
      var options = { day: "numeric", month: "long", year: "numeric" };
      let local = dat.toLocaleDateString("en-US", options);
      console.log(local); // 22 Sep 1995

2 个答案:

答案 0 :(得分:3)

您可以为此使用DatePipe

Stackblitz

import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [DatePipe]
})
export class AppComponent {
    constructor(private datePipe: DatePipe){
       console.log(this.datePipe.transform("1995-09-22", 'dd MMM yyyy'))
    }
}

答案 1 :(得分:0)

请尝试这样:

  let dat = new Date("1995-09-22");
  var options = { day: "numeric", month: "long", year: "numeric" };
  let local = dat.toLocaleDateString("en-US", options);
  console.log(local); // 22 Sep 1995

仅供参考:未经测试的代码