DEV Community

Cover image for Angular Hidden Time Pipe
Ibrahim Zahema
Ibrahim Zahema

Posted on

Angular Hidden Time Pipe

I was integrating an API when I found myself faced with this data format:

dateRange: {
  date: '2020/02/02',
  fromTime: '10:00',
  toTime: '13:30',

It was required to display the date in the following format:
2 Feb 2020 [10:00 AM- 01:30 PM]

Now you might have noticed the time field is in 24 hours format while we need 12 hours format.
A time pipe would be perfect for this, except seemingly Angular doesn't include one!

I was about to try my luck with some 3rd party pipe but I wasn't comfortable with including a dependency for such a simple pipe. Should I build it myself?

Then I had an idea, maybe I can construct a date object from the time portion? I don't care what day/month it is; I will be just displaying the time portion anyway right?
Even better... what if:

{{ + ' ' + dateRange.toTime | date: 'hh:mm aa'}}
<!-- Output -->
<!-- 01:30 PM -->


{{'01/01/1900 ' + dateRange.toTime | date: 'hh:mm aa'}}
<!-- Output -->
<!-- 01:30 PM -->


Yeah, we just use the date pipe but append a day/month/year string ahead of the time portion.

This is my first technical "artical" -if we can call it that. Wanted to start simple and I didn't counter any mention of this "trick" online.
Any feedback is appreciated ^^.

Top comments (1)

esraaqandel profile image

Nice trick!