How to Change the Time Format (12/24 Hours) of an <Input>

How to change the time format (12/24 hours) of an input?

HTML5 Time Input

This one is the simplest of the date/time related types, allowing the user to select a time on a 24/12 hour clock, usually depending on the user's OS locale configuration. The value returned is in 24h hours:minutes format, which will look something like 14:30.

More details, including the appearance for each browser, can be found on MDN.

<input type="time" name="time">

HTML input time in 24 format

As stated in this answer not all browsers support the standard way. It is not a good idea to use for robust user experience. And if you use it, you cannot ask too much.

Instead use time-picker libraries. For example: TimePicker.js is a zero dependency and lightweight library. Use it like:

var timepicker = new TimePicker('time', {
lang: 'en',
theme: 'dark'
});
timepicker.on('change', function(evt) {

var value = (evt.hour || '00') + ':' + (evt.minute || '00');
evt.element.value = value;

});
<script src="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>
<link href="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet"/>

<div>
<input type="text" id="time" placeholder="Time">
</div>

How to change time from 24 to 12 hour format in angular 5

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!!

Html5 time input 24 hours

At the moment, HTML5 time format is 24-hour format.

  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time

If you are looking for 3rd party libraries with a little configuration to convert back and forth between 12 and 24 hour format or accept input in either/both, there are many out there. I use this component in production, currently. You may wish to create your own component or use different components/libraries.

Also, simple mathematics can be used to convert 12 to 24 hour time and vice versa, and you can find that easily by Googling - that is not going to change dependent on the browser.

Demos here:

  • http://jdewit.github.io/bootstrap-timepicker/

Download as ZIP here:

  • https://github.com/jdewit/bootstrap-timepicker

I use this in conjunction with moment.js:

  • https://momentjs.com/


Related Topics



Leave a reply



Submit