9

I have used input type time in my application to receive time:

  <mat-input-container>
<input matInput  formControlName="start_time" type="time" placeholder="Time Start">
<p class="invalid-text" *ngIf="dvrForm.controls.start_time.invalid &&
        (dvrForm.controls.start_time.dirty || dvrForm.controls.start_time.touched)">
  <span *ngIf="dvrForm.controls.start_time.errors.required"> Start Time is required.</span></p>

And after i store data through input it gets stored in 24 hour format :

View Of database how the time is stored

So now when I display it in my view it gets displayed in the same format eg: 23:11:00 , is it possible to use something like pipes to convert it into 12 hr format while displaying in the view.

Atul Stha
  • 1,404
  • 8
  • 23
  • 46

8 Answers8

13

Yes, you can do it from pipe:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'convertFrom24To12Format'})
export class TimeFormat implements PipeTransform {
     transform(time: any): any {
         let hour = (time.split(':'))[0]
         let min = (time.split(':'))[1]
         let part = hour > 12 ? 'pm' : 'am';
         if(parseInt(hour) == 0)
          hour = 12;
         min = (min+'').length == 1 ? `0${min}` : min;
         hour = hour > 12 ? hour - 12 : hour;
         hour = (hour+'').length == 1 ? `0${hour}` : hour;
         return `${hour}:${min} ${part}`
       }
   }

In your html for example:

<p>Time Format From  24 to 12 : {{'23:11:00' | convertFrom24To12Format}}</p>

Hope this will help you!!

Sarah
  • 346
  • 1
  • 3
  • 11
Sanoj_V
  • 2,936
  • 1
  • 12
  • 28
8

With Pipe you can achive it you need to use hh for 12h and HH for 24h

var value = element(by.binding('example.value | date: "HH:mm:ss"'));
    var valid = element(by.binding('myForm.input.$valid'));

    function setInput(val) {
      var scr = "var ipt = document.getElementById('exampleInput'); " +
      "ipt.value = '" + val + "';" +
      "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
      browser.executeScript(scr);
    }
<script src="//code.angularjs.org/1.7.0/angular.min.js"></script>
    <body ng-app="timeExample">
      <script>
     angular.module('timeExample', [])
       .controller('DateController', ['$scope', function($scope) {
         $scope.example = {
           value: new Date()
         };
       }]);
    </script>
    <form name="myForm" ng-controller="DateController as dateCtrl">
       <label for="exampleInput">Pick a time and Change AM to PM</label>
       <input type="time" id="exampleInput" name="input" ng-model="example.value"
           placeholder="HH:mm:ss"  required /><br/>
       <tt>value in 12H = {{example.value | date: "hh:mm:ss"}}</tt><br/>
       
       <tt>value 24H = {{example.value | date: "HH:mm:ss"}}</tt>

    </form>
    </body>
v8-E
  • 1,077
  • 2
  • 14
  • 21
  • i dont recieve the value in time stamp format, as I mentioned I receive time in time format that is `11:11:00` due to which i get the error `DvrListComponent.html:40 ERROR Error: InvalidPipeArgument: '11:11:00' for pipe 'DatePipe'` – Atul Stha May 16 '18 at 06:04
  • '11:11:00' is not a timestamp, it is a string. If you have to start dealing with timezones, a string is insufficient. Converting a timestamp with HH instead of hh should be the way to go. – Guntram Oct 07 '19 at 10:46
7

For future reference, using the default Angular pipe reference UPPERCASE HH.mm instead of hh.mm

today: Date = new Date('2020-12-12T18:00');

<div> {{ today | date : 'hh.mm' }}</div>
// 06.00
<div>{{ today | date : 'HH.mm' }}</div>
// 18.00
Nadhir Falta
  • 5,047
  • 2
  • 21
  • 43
1

You can use mediumTime, this displays like '10:30:24 AM'

{{start_time|date:'mediumTime':'undefined':'en-US' }}

0

Yes you can convert the time from 24 hours to 12 hours format using moment library. You can create a custom pipe to achieve it. Refer the following youtube link it solves the similar issue.

https://www.youtube.com/watch?v=vKE1d9o_Kmk

  • Would not reccommend using moment. 'Moment.js is a legacy project, now in maintenance mode. In most cases, you should choose a different library.' https://github.com/moment/moment – Lars Rødal Jul 31 '21 at 21:36
  • @LarsRødal, Yes I know that, With that the Moment.js team has also announced as "_ It is not dead, but it is indeed done._". Which means, they’ll fix any serious issues but new features or changes are off the table. So I don't see any reason for down voting this answer. And definitely we can use moment existing features in our project till it is announced as officially dead. – user3741852 Aug 01 '21 at 16:30
-1

You can use the Datepipe https://angular.io/api/common/DatePipe

You can pass the Datepipe the locale parameter which determines how your date is displayed.

e.g

{{this.testDate | date:'short':'undefined':'en-US'}}

will display as 11:20 AM

{{this.testDate | date:'short':'undefined':'de-GER'}}

will display as 16.05.18, 11:20

You could also set your localeid in the app-module.ts to get the behaviour

app-module.ts

import localeEnGb from '@angular/common/locales/en-GB'
registerLocaleData(localeEnGb );
...
  providers: [
    { provide: LOCALE_ID, useValue: 'en-GB' }
]
lynxSven
  • 555
  • 1
  • 10
  • 27
-1

try this pipe

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

@Pipe({
  name: 'dateConvert'
})
export class DateConvertPipe implements PipeTransform {

  transform(d: string): string {
    const date = new Date(d);
    date.toLocaleString('fr-FR', {
      hour: 'numeric',
      hour12: true
    });
    const monthNames = [
      'Janv', 'Févr', 'Mars',
      'Avr', 'Mai', 'Juin', 'Juill',
      'août', 'Sep', 'Oct',
      'Nov', 'Dec'
    ];
    const day = date.getUTCDay();
    const monthIndex = date.getMonth();
    const year = date.getFullYear();
    const hours = date.getHours();
    const min = date.getMinutes();
    const sec = date.getSeconds();
    return day + ' ' + monthNames[monthIndex] + ' ' + year + ' ' + hours + ':' + min + ':' + sec;
  }

}
<span>{{ s.subscriptionDate | dateConvert}}</span>
Oscar
  • 157
  • 1
  • 9
-1

You can try this, {{'1970-01-01 ' + start_time | date: 'h:mm:ss a'}}

Reason is input string should always be a valid date with a time

Vindhya
  • 49
  • 7