InvalidPipeArgument:'无法将管道'DatePipe'

时间:2019-03-11 09:12:02

标签: javascript angular typescript ecmascript-6 date-pipe

 <td>{{suite.testSuiteAttributes && 
       suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd'
     }}
</td>

我希望Date格式为“ CST 05 / Feb-2018 11:00:00” CST格式。但是出现错误:

  

无法将“ 2018-01-01-12:12:12:123456”转换为管道的日期   'DatePipe

我认为是由于timeStamp的日期格式不是..而是仅从后端获取此日期。请提出建议。

2 个答案:

答案 0 :(得分:1)

您的日期“ 2018-01-01-12:12:12:123456”不是有效的ISO 8601 date,因此内置解析器无法对其进行解析。使用有效的日期格式或编写自定义解析器。

您可以使用正则表达式或简单地使用诸如子字符串之类的字符串函数,如其他答案所示。

Javascript中的日期将位于浏览器的本地时区,即用户的系统时间,没有本地方法可以在其他时区中创建日期。您可以使用UTC创建日期,并使用toLocaleString()将日期转换为特定的时区。取决于从后端发送的日期是UTC还是CT。如果是CT,则仅适用于CT时区的用户。

let result = "2018-01-01-12:12:12:123456".match(/(\d{4})-(\d{2})-(\d{2})-(\d{2}):(\d{2}):(\d{2}):(\d{3})/).map(x => parseInt(x, 10));

result.shift();

console.log(new Date(...result).toLocaleString())

答案 1 :(得分:0)

我认为您从服务器获取的格式日期错误。您需要使用有效格式的日期进行转换

因此,这是针对您的问题的解决方法,其中我编写了 myDateParser() 方法将无效日期转换为有效日期。

your.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  modifiedTimestamp;

 constructor(){

   // Passing unformatter date
   this.modifiedTimestamp = this.myDateParser('2018-01-01-12:12:12:123456');
 }

 /**
  * Custom Date parser

  */
  myDateParser(dateStr : string) : string {
    // 2018-01-01T12:12:12.123456; - converting valid date format like this

    let date = dateStr.substring(0, 10);
    let time = dateStr.substring(11, 19);
    let millisecond = dateStr.substring(20)

    let validDate = date + 'T' + time + '.' + millisecond;
    console.log(validDate)
    return validDate
  }
}

your.component.html

  <table>
    <tr>
     <td>{{modifiedTimestamp |  date: 'yyyy-MM-dd'}}</td>
    </tr>
   </table>

Solution on stackblitz

希望这会有所帮助!

相关问题