Kevin Jose
Kevin Jose

Reputation: 876

How to display time in HH:MM format in Ionic 3

Am getting time from API as in the format 13:45:56 and i wanna display it as 13:45(HH:MM) . Can anyone help me? I tried to use Date pipe along with the binding tag, but it throws an error as

 InvalidPipeArgument: '23:00:00' for pipe 'DatePipe'

Upvotes: 2

Views: 2351

Answers (5)

Kevin Jose
Kevin Jose

Reputation: 876

thank you guys for your valuable comments . Appreciating your efforts. I fixed it by using a pipe. it will be look bit complex, but really useful for applying in multiple queries. Adding pipe query here with

datepipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'datepipe' })
export class DateSet implements PipeTransform {
  transform(timeString: string ) {
    let time;
    time = timeString.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [timeString];
    if (time.length > 1) { // If time format correct
      time = time.slice (1);  // Remove full string match value
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
      time[3] = ' ';
      time[4] = ' ';
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    return time.join ('');
  }
}

Upvotes: 2

ZearaeZ
ZearaeZ

Reputation: 905

I have created a stackblitz for your solution. This project might help you.

Upvotes: 0

vaibhav
vaibhav

Reputation: 4103

You can bind it in the following way as well:

<span class="dt-time">{{ entity.created_at | utcTimeConversion: utcOffset : "MMM DD YYYY"}}</span>

Here i am also taking into consideration the UTC offset alongside the format, this would ensure that the mobile device converts the time as per the timezone of the device..

Cheers!

Upvotes: 1

f.loris
f.loris

Reputation: 1041

Angular's DatePipe expects a date according to the docs:

....a Date object, a number (milliseconds since UTC epoch), or an ISO string.

So you need to convert your time from the API to one of these if you want to format it via Angular.

Btw, is it no option to just remove the second part of your time string which you get from the API?

Upvotes: 0

PUSHPRAJ KUMAR
PUSHPRAJ KUMAR

Reputation: 1

HH - Hour, 24-hour, leading zero 00 ... 23 h - Hour, 12-hour 1 ... 12 hh - Hour, 12-hour, leading zero 01 ... 12

m - Minute 1 ... 59 mm - Minute, leading zero 01 ... 59

So you can simply write HH:mm

EX: <ion-datetime display-format="HH:mm"></ion-datetime>

Upvotes: 0

Related Questions