我的日期格式为“2020-02-07T16:13:38.22”,我想将其转换为“d MMMMM yyyy HH:mm a”,而不使用 momentjs。
下面的方法用于转换日期
const options = {
day: "numeric",
month: "long",
year: "numeric",
}
var date1 = new Date("2020-02-07T16:13:38.22").toLocaleDateString("en-US", options);
const options1 = {
hour12: true,
hour: "numeric",
minute: "2-digit",
}
var date2 = new Date("2020-02-07T16:13:38.22").toLocaleTimeString("en-US", options1);
var res = date1 + ', ' + date2;
console.log(res)
上面的代码给出的结果是“2020年2月7日下午4:13”,但我需要“2020年2月7日下午4:13”,即先是日期,然后是月份、年份和时间,我尝试的代码更长,请帮忙我得到了所需的结果。
最佳答案
在 Angular 中,我发现注入(inject)日期管道以进行复杂的日期格式化是最简单的
import { DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers: [
DatePipe
]
})
export class AppComponent implements OnInit {
constructor(private datePipe: DatePipe) {
}
formatted: string;
ngOnInit(): void {
const d = new Date();
this.formatted = this.datePipe.transform(d, 'd MMMM yyyy h:mm a');
}
}
工作示例:stackblitz
注意,我通常会在 html 中格式化它,但看起来您正在要求 typescript 解决方案。
关于javascript - javascript 中的日期转换为 (d MMMMM yyyy HH :mm am) without momentjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60117631/