【问题标题】:How to format the date 19990813 (YYYY-MM-DD) to 13.08.1999 (DD-MM-YYYY) with the the dots?如何用点将日期 19990813 (YYYY-MM-DD) 格式化为 13.08.1999 (DD-MM-YYYY)?
【发布时间】:2019-05-02 07:43:27
【问题描述】:

我无法将后端给出的字符串类型的日期 19990813 转换为带点的 13.08.1999。我不能这样做..

使用 Angulars in-build date-format-function 我总是得到错误的日期。

我怎样才能实现我的目标?

感谢您的任何建议。

亲切的问候

安娜玛丽

【问题讨论】:

  • 你想让它成为管道操作员吗?如果您在模板中使用它,这是首选。
  • 如果我告诉你日期 19990813 (YYYY-MM-DD) 实际上的格式是 YYYYmmDD ??
  • 如果它是首选,我想使用它:)。我得稍微搜索一下。感谢您的建议
  • 是的,@AnnaMarie,出于性能原因,您绝对应该使用管道运算符。我会在几分钟后发布它的代码。
  • Moment 管道在这里,但您需要将pipes 放入app.module stackoverflow.com/questions/38490410/…

标签: javascript angular typescript date


【解决方案1】:

你可以安装npm i moment并像这样使用

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

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

【讨论】:

  • 同样的时刻管道在这里,但你需要把管道放在 app.module stackoverflow.com/a/38491960/4711754
  • 是的,如果你需要在其他文件中使用这种格式,你应该为它创建一个自定义管道
  • 我真的看不出需要日期库来重新格式化需要单个表达式的字符串。您也可以在此处将代码发布为可运行的 sn-p。
  • 我建议momentjs,因为他们可能在实际项目中需要更多格式
【解决方案2】:

您可以为此使用String replace()

let date = `19990813`

let regex = /^(\d{4})(\d{2})(\d{2})$/

let newDate = date.replace(regex, "$3.$2.$1")
console.log(newDate)

【讨论】:

  • 或者只是date.replace(/(\d{4})(\d\d)(\d\d)/, "$3.$2.$1")。 :-)
  • @RobG 是的,但我觉得按照另一个答案中的建议与库约会是件好事。它们将被优化和测试。
【解决方案3】:

如果您需要在组件的模板中进行这种字符串转换,最好的选择(出于性能原因)是使用管道运算符。

对字符串转换本身使用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 模块中。

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多