我在将后端给定的字符串类型的日期19990813转换为带点的13.08.1999时遇到问题。我无法这样做。.
使用Angulars内置的日期格式功能,我总是得到错误的日期。
我如何实现我的目标?
感谢您的任何建议。
亲切的问候
安娜·玛丽
答案 0 :(得分:5)
您可以安装npm i moment
并像这样使用
datestring = '19990813';
constructor(){
let date = moment(this.datestring, 'YYYYMMDD');
let datedot = date.format('DD.MM.YYYY');
alert(datedot);
}
答案 1 :(得分:3)
您可以为此使用String replace()。
let date = `19990813`
let regex = /^(\d{4})(\d{2})(\d{2})$/
let newDate = date.replace(regex, "$3.$2.$1")
console.log(newDate)
答案 2 :(得分:0)
如果您需要在组件模板中执行此字符串转换,出于性能原因,最好的选择是使用管道运算符。
将xyz提出的解决方案用于字符串转换本身。
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'myDateFormat'
})
export class MyDateFormatPipe implements PipeTransform {
transform(value: string, args?: any): any {
if (!value) {
return value;
} else {
// process the 'value' param and return its result according to xyz's solution
}
}
}
然后在您的模板中,像这样使用它:
inputDate | myDateFormat
其中inputDate为'19990813'。
不要忘记将此类导入将使用它的angular模块。