As per my recent task in my project I had to convert time to 24 hours format. The time was in format of 12:30 am or 2:30 pm. Hence I thought of writing a function that will convert as per requested formats. Please find the function below. I hope this will help in saving a good amount of time in finding the logic to convert time format.
<script type="text/javascript">
function timeFormat(format, str){
var timeParts = str.split(":");
var fstPart = timeParts[0];
var sndPart = timeParts[1];
var sndPartNum = sndPart.match(/\d+/)[0];
if(sndPart.match(/[a-zA-Z]+/)){
var sndPartStr = sndPart.match(/[a-zA-Z]+/)[0];
}else{
var sndPartStr = '';
}
if(format==12){
if(sndPart.match(/[a-zA-Z]+/)
&& sndPart.match(/[a-zA-Z]+/).length
&& fstPart <= 12){
return fstPart + ":" + sndPartNum + " " + sndPartStr;
}
else if(!sndPart.match(/[a-zA-Z]+/)){
if(fstPart <= 12){ // AM part
return fstPart + ":" + sndPartNum + " am";
}else if(fstPart > 12 && fstPart < 24){ // PM Part
return parseInt(fstPart) - 12 + ":" + sndPartNum + " pm";
}else{
alert('the input value is not in proper format.');
return false;
}
}else{
alert('the input value is not in proper format.');
return false;
}
}else if(format == 24){
if(fstPart < 24){
var hours = parseInt(fstPart);
if(sndPartStr.toLowerCase() == "pm"){
hours += 12;
}
return hours + ":" + sndPartNum;
}else{
alert('the input value is not in proper format.');
return false;
}
}
}
// Calling the method with different type of values
console.log('input: 2:30 pm. Convert to 24 hours format');
console.log(timeFormat(24, '2:30 pm'));
console.log('input: 2:30 am. Convert to 24 hours format');
console.log(timeFormat(24, '2:30 am'));
console.log('input: 22:30. Convert to 12 hours format');
console.log(timeFormat(12, '22:30'));
console.log('input: 2:30. Convert to 12 hours format');
console.log(timeFormat(12, '2:30'));
console.log('input: 2:30 am. Convert to 12 hours format');
console.log(timeFormat(12, '2:30 am'));
console.log('input: 18:00. Convert to 12 hours format');
console.log(timeFormat(12, '18:00 am'));
</script>