将格式从d-mmm-yyyy到yyyy-mm-d的日期格式化为angular 2

时间:2020-09-09 00:20:02

标签: javascript angular typescript date

使用datepipe在angular 2中的日期以下格式化的最佳方法是什么?

我正在尝试使用以下格式设置日期格式:d-mmm-yyyy到yyyy-mm-d

例如,从2019年11月1日到2019-11-1或从2018年12月15日到2018-12-15

我必须使用内置的日期管道来完成此操作。

6 个答案:

答案 0 :(得分:0)

如何在JS中使用Date类?

const d = new Date("1-Nov-2019");

function transform(d) {
  return `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}`
}

console.log(transform(d));

或将此函数附加到Date类中,如下所示:

Date.prototype.transform = function() {
  return `${this.getFullYear()}-${this.getMonth()+1}-${this.getDate()}`
}

console.log(d.transform());

答案 1 :(得分:0)

类似的事情应该可以解决问题

{{ myDate | date :'yyyy-mm-d' }}

完整文档在这里:https://angular.io/api/common/DatePipe

答案 2 :(得分:0)

const date = new Date()
  .toISOString()
  .slice(0, 10)
  .split("-")
  .reverse();
console.log(date);

答案 3 :(得分:0)

import { DatePipe } from '@angular/common';
...

@Component({
  providers: [DatePipe],
  ...
})

constructor(private datePipe: DatePipe) { }

// use the following where you need
this.datePipe.transform(yourDate, 'yyyy-mm-d');

答案 4 :(得分:0)

您可以使用moment.js库并在ts中更改日期,然后将其显示在模板上

moment(yourDate).format('yyyy-mm-d')

您可以在模板中设置日期格式

{{ yourDate | date :'yyyy-mm-d' }}

答案 5 :(得分:0)

您可以使用类似的东西

import { DatePipe } from "@angular/common";
export class AppComponent implements OnInit {
 pipe = new DatePipe('en-US');
 todayWithPipe = null;
 ngOnInit(): void {
  this.todayWithPipe = this.pipe.transform(Date.now(), 'yyyy.MM.dd');
 }}

<h3> Date in YYYY.MM.DD Format </h3>
<p>{{ todayWithPipe }}</p>