I have a output resulting from a timepicker giving 12 hour format of time.
Eg : \"1:45 AM (or) \"12:15 PM\" as **string**
Is there a way to par
Here's how you can set the time of a Date
object using a time String
.
const date = new Date('1/1/21');
const pm = '2:30 PM';
const am = '11:00 AM';
const noon = '12:00 PM';
const midnight = '12:00 AM';
const mergeDateTime = (date, time) => {
const parsedTime = moment(time, ['h:mm A']);
const merged = moment(date).set({
hours: parsedTime.get('hours'),
minutes: parsedTime.get('minutes')
});
return merged.toDate();
};
const resultsList = document.querySelector('#results');
const inputs = [pm, am, noon, midnight];
inputs.forEach((input) => {
const li = document.createElement('li');
li.innerText = `${input} ➡ ${mergeDateTime(date, input)}`;
resultsList.appendChild(li);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<h3>Results</h3>
<ul id=results />
moment("145","hmm").format("HH:mm");
this would result in 01:45
See documentation of moment js parse function
JSFiddle
var dt = moment("12:15 AM", ["h:mm A"]).format("HH:mm");
Just a little conversation "2 PM" to "14.00"
const number = moment("02:00 PM", ["h:mm A"]).format("HH:mm");
cosole.log(number); // "14.00"
"14.00" to "2 PM"
const number = moment("14.00", ["HH.mm"]).format("hh:mm a");
cosole.log(number); // "02:00 pm"
In full calender to show time in 12 hour format like 01:00 PM i used following format - timeFormat: 'hh:mm A'. "timeFormat" is the property of events of fullcalender.
Same format 'hh:mm A' we can use to format datetime object using momentjs.
I know that this answer is not for the question (actually it is for the opposite case), but I will put it for completeness and if someone (like me) was looking for it.
In case you want to convert from the 24 Hour system
to 12 Hour system
then you could use the following
return moment("13", ["HH"]).format("hh A");
the previous code will produce the result 1 PM