Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 12 hour (AM/PM) string to 24 Date object using moment js

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 parse this string format to 24 hour using moment js back to date object?

like image 241
ram Avatar asked Nov 06 '14 15:11

ram


People also ask

How do you set 24 hour format in moment?

We can use the H or HH formatting tag to format the hour of a date-time as a 24-hour format time.

How do you convert a string to a moment object?

We can parse a string representation of date and time by passing the date and time format to the moment function. const moment = require('moment'); let day = "03/04/2008"; let parsed = moment(day, "DD/MM/YYYY"); console.

How do you show AM PM with a moment?

To get am pm from the date time string using moment. js and JavaScript, we use the 'A' format code. console. log( moment("Mon 03-Jul-2022, 11:00 AM", "ddd DD-MMM-YYYY, hh:mm A").


3 Answers

See documentation of moment js parse function

JSFiddle

var dt = moment("12:15 AM", ["h:mm A"]).format("HH:mm");
like image 134
Pochen Avatar answered Oct 18 '22 03:10

Pochen


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

like image 34
Hakan Fıstık Avatar answered Oct 18 '22 03:10

Hakan Fıstık


Just a little conversation "2 PM" to "14.00"

const number = moment("02:00 PM", ["h:mm A"]).format("HH:mm");
console.log(number); // Output = "14.00"

"14.00" to "2 PM"

const number = moment("14.00", ["HH:mm"]).format("hh:mm a");
console.log(number); // Output = "02:00 pm"
like image 20
Neel Rathod Avatar answered Oct 18 '22 03:10

Neel Rathod