Formatting a Time value on Ionic 3

I need to find the way to format a time, I tried with angular pipe, but this works with date type values.

I need to be able to remove the seconds to values of the hours shown, example:

1:45:00 change to 1:45 pm or 1:45 p.m. M.

Upvotes: 0

Views: 1293

Answers (4)

Marina Osama
Marina Osama

Reputation: 61

you can use a custom pipe 

transform(timeString: string) {
    let time = timeString.slice(0, 5);
    let current_hour = timeString.slice(0, 2);
    if (parseInt(current_hour) > 12) {
      time = time + " PM";
    } else {
      time = time + " AM";
    }
    return time;
  }

Upvotes: 0

rashmi ranjan
rashmi ranjan

Reputation: 388

Use Moment.js .here you can convert to any time format

1 - Install via NPM:

npm install moment -S

2 - Import in your Typescript file:

import moment from 'moment';

3 - Use in your Typescript file:

let dateString = "22-04-2017"; //whatever date string u have
let dateObject = moment(dateString, "DD-MM-YYYY").toDate();

Upvotes: 2

Phonolog
Phonolog

Reputation: 6511

Assuming your date is a instance of Date you can use the built in angular date pipe with the predefined format shortTime or a custom format:

<p> {{date | date:'shortTime'}} </p>

<p> {{date | date:'hh:mm'}} </p>

shortTime is equivalent to 'h:mm a' and will produce results like 9:03 AM.

The custom format 'hh:mm' will produce results like 09:03.


If your date is just a string you could use the built in slice pipe to remove the parts you want to get rid of:

<p> {{"1:45:00" | slice:0:4}} </p>

Which will output 1:45.

Also see this Stackblitz for the different options.

Anyway I'd reccomend using real Date objects or Moment.js objects over bare strings, it makes things a lot easier, especially once you start comparing dates or calculating with dates.

Upvotes: 2

Shannon
Shannon

Reputation: 914

If this is format is always the case you can manipulate the string with JavaScript/TypeScript.

  myTime = '1:45:00'

  showTime() {
    var result = 
    this.myTime.substring(
      0, (this.myTime.length - 3) )+ ' pm';
    console.log(result);
  }

If you have more complicated cases You could use a library like Momentjs. https://momentjs.com/

This is where you can find what you need in the docs. https://momentjs.com/docs/#/parsing/string-format/

Upvotes: 0

Related Questions