简体   繁体   English

如何用点将日期19990813(YYYY-MM-DD)格式化为13.08.1999(DD-MM-YYYY)?

[英]How to format the date 19990813 (YYYY-MM-DD) to 13.08.1999 (DD-MM-YYYY) with the the dots?

I have problem to convert the date 19990813 of type string given by the backend to 13.08.1999 with the dots. 我在将后端给定的字符串类型的日期19990813转换为带点的13.08.1999时遇到问题。 I am not able to do so.. 我无法这样做。

Using Angulars in-build date-format-function I got always the wrong date. 使用Angulars内置日期格式功能,我总是得到错误的日期。

How can I achieve my goal? 我如何实现我的目标?

I am thankful for any advice. 感谢您的任何建议。

Kind regards 亲切的问候

Anna Marie 安娜·玛丽(Anna Marie)

You can install npm i moment and use like this 您可以立即安装npm i moment并像这样使用

datestring = '19990813';
  constructor(){
     let date = moment(this.datestring, 'YYYYMMDD');
     let datedot = date.format('DD.MM.YYYY');
     alert(datedot);
  }

Demo https://stackblitz.com/edit/moment-js-format 演示https://stackblitz.com/edit/moment-js-format

You can use String replace() for this. 您可以为此使用String replace()

 let date = `19990813` let regex = /^(\\d{4})(\\d{2})(\\d{2})$/ let newDate = date.replace(regex, "$3.$2.$1") console.log(newDate) 

If you need to do this string transformation in a component's template, the best choice (for performance reasons) is to use a pipe operator. 如果您需要在组件模板中执行此字符串转换,则最佳选择(出于性能原因)是使用管道运算符。

Use the solution proposed by xyz for the string transformation itself. 将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
        }
    }
}

then in your template, use it like this: 然后在您的模板中,像这样使用它:

inputDate | myDateFormat

where inputDate is '19990813'. 其中inputDate为'19990813'。

And don't forget to import this class to the angular module that will use it. 并且不要忘记将此类导入将使用它的angular模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM