I am trying to convert a String that consist of "AM" or "PM" into a 24 hours format. I have tried using formatDate but couldn't able to get the outcome that I would like. The following are examples of the values that I am trying to convert from String into a 24 hours format String.
String (Before) | String (After) |
---|---|
10:00AM | 10:00 |
12:00PM | 12:00 |
02:00PM | 14:00 |
04:00PM | 16:00 |
Is using formatDate a recommended approach in this case or if not what other possible methods or way am I able to convert this String into the format above without complicating the codes?
CodePudding user response:
By using javascrpit, you can also convert "AM" or "PM" into a 24 hours format :
var time = $("#starttime").val();
var hours = Number(time.match(/^(\d )/)[1]);
var minutes = Number(time.match(/:(\d )/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours 12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" sHours;
if(minutes<10) sMinutes = "0" sMinutes;
alert(sHours ":" sMinutes);
CodePudding user response:
You can use Momentjs to conver "AM" or "PM" into a 24 hours format.
console.log(moment("10:00 AM", "h:mm A").format("HH:mm"));
console.log(moment("12:00 PM", "h:mm A").format("HH:mm"));
console.log(moment("2:00 PM", "h:mm A").format("HH:mm"));
console.log(moment("4:00 PM", "h:mm A").format("HH:mm"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>