[英]How to format the date 19990813 (YYYY-MM-DD) to 13.08.1999 (DD-MM-YYYY) with the the dots?
我在將后端給定的字符串類型的日期19990813轉換為帶點的13.08.1999時遇到問題。 我無法這樣做。
使用Angulars內置日期格式功能,我總是得到錯誤的日期。
我如何實現我的目標?
感謝您的任何建議。
親切的問候
安娜·瑪麗(Anna Marie)
您可以立即安裝npm i moment
並像這樣使用
datestring = '19990813';
constructor(){
let date = moment(this.datestring, 'YYYYMMDD');
let datedot = date.format('DD.MM.YYYY');
alert(datedot);
}
您可以為此使用String replace() 。
let date = `19990813` let regex = /^(\\d{4})(\\d{2})(\\d{2})$/ let newDate = date.replace(regex, "$3.$2.$1") console.log(newDate)
如果您需要在組件模板中執行此字符串轉換,則最佳選擇(出於性能原因)是使用管道運算符。
將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模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.