Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular DatePipe - Convert seconds to time with zero timezone (12 instead of 00)

I want to convert number (which represents seconds) using DatePipe to get result like this :

00:00:05

I've tried doing so with DatePipe this way:

<label>No timezone (default) {{ 5 * 1000 | date:'h:mm:ss'}}</label>

But it produces result with timezone +4 included (which is not what I want):

4:00:05

So in order to avoid this I'm trying to set timezone offset to 0:

<label>{{ 5 * 1000 | date:'h:mm:ss z':'+0000'}}</label>
<label>{{ 5 * 1000 | date:'h:mm:ss z':'UTC'}}</label>
<label>{{ 5 * 1000 | date:'h:mm:ss z':'GMT'}}</label>
<label>{{ 5 * 1000 | date:'h:mm:ss z':'GMT+0'}}</label>
<label>{{ 5 * 1000 | date:'h:mm:ss z':'UTC+0'}}</label>

But this time the time is shifted with 12 hours instead of 0:

12:00:05 GMT+0

So is there a way to convert seconds to time with DatePipe without shifted timezone?
Or is there any other pipe by angular which can be used for this purpose?

like image 924
Just Shadow Avatar asked Sep 13 '18 20:09

Just Shadow


People also ask

What is DatePipe in angular?

DatePipe is used to format a date value according to locale rules. Syntax: {{ value | date }} Approach: Create the angular app that to be used. There is no need for any import for the DatePipe to be used.


2 Answers

So this quite tricky problem has a quite simple solution.
We just have to use 'H' instead of 'h' (range of which is 0-23).
Example:

<label>{{ 5 * 1000 | date:'H:mm:ss':'UTC'}}</label>

The reason of getting '12' was the usage of 'h' in time format which limits values from 1 to 12 and converts 00:00 to 12:00 (AM).

enter image description here

like image 140
Just Shadow Avatar answered Sep 30 '22 00:09

Just Shadow


This is very easy with MomentJS

const SECONDS_COUNT = 61;

const duration = moment.duration(SECONDS_COUNT, 'seconds');
const resultstring = moment.utc(duration.asMilliseconds()).format('HH:mm:ss');
console.log(resultstring);

should output 00:01:01

make sure you use moment.utc() to output and not moment() to avoid locale settings kicking in.

like image 30
Stavm Avatar answered Sep 30 '22 01:09

Stavm