10

I was using a custom pipe for displaying time, and now I tried to change it so that I could also display milliseconds:

{{log.LogDate|jsonDate|date:'dd.MM.yyyy   HH:mm:ss.sss'}}

The pipe itself:

if (typeof (value) === 'string') {
        if (value.includes('/Date('))
            return  new Date(parseInt(value.substr(6)));
    }
    return value;

However, milliseconds have the value of seconds:

log.LogDate: 2017-05-08T15:45:38.2527293+ 02:00

Output from pipe: 08.05.2017 15:45:38.38

Full jsonDate pipe(no format): 2017-05-08T15:45:38.2527293+02:00

I am new to Javascript, and I am not sure if this is an Javascript or an Angular issue, however, I would like it to work inside Angular. Is it possible to do this using pipes, or is there another/better way to do this?

Schattenjäger
  • 331
  • 1
  • 3
  • 13

3 Answers3

16

Since angular 5 you can use SSS to add milliseconds to your date.
See https://angular.io/api/common/DatePipe


So your example would look like

{{log.LogDate|jsonDate|date:'dd.MM.yyyy   HH:mm:ss.SSS'}}



Changelog for angular 5:
- [...]
- fractional seconds are now supported with the format S to SSS.
- [...]

Akora
  • 756
  • 7
  • 22
7

It's an Angular issue. AngularJS supports milliseconds, but Angular (2+) does not (GH issue). You can very well drop the date pipe and use only your custom one for this task. Your example however doesn't seem to handle dates very well. Without going into details I suggest you use some external library to do the formatting for you inside your pipe. Otherwise it would be a lot of effort for little reward. My personal weapon of choice is Moment.js After importing it correctly you would simply use:

moment(value).format('DD.MM.YYYY HH:mm:ss.SSS');

If you want a dirty way out of this without importing external libraries, you could use Angular date pipe as it is (with seconds only) and then pipe it to add milliseconds on your own.

borkovski
  • 938
  • 8
  • 12
0

Another possibility is to stay with angulars pipe and extract the milliseconds via javascript-method:

{{ Datetime | date:'dd.MM.yyyy HH:mm:ss' }}.{{ getMillies(Datetime) }}

----

public getMillies(input: Date): number
{
    return new Date(input).getMilliseconds();
}

With Angular 5, a new Date-Pipe is in progress, to support M

J.Starkl
  • 2,183
  • 1
  • 13
  • 15