24小时时间转为12小时制
function convertTo12Hour ( time24h ) {
let [ hours, minutes] = time24h. split ( ':' ) ;
let modifier = '上午' ;
if ( parseInt ( hours, 10 ) > 12 ) {
modifier = '下午' ;
hours = ( parseInt ( hours, 10 ) - 12 ) . toString ( ) ;
}
if ( parseInt ( hours, 10 ) === 12 ) {
modifier = '下午' ;
}
if ( parseInt ( hours, 10 ) === 0 ) {
hours = '00' ;
}
return ` ${ hours. padStart ( 2 , '0' ) } : ${ minutes} ${ modifier} ` ;
}
convertTo12Hour ( '18:30' )
convertTo12Hour ( '00:30' )
convertTo12Hour ( '09:00' )
12小时时间转为24小时制
function convertTo24Hour ( time12h ) {
const [ time, modifier] = time12h. split ( ' ' ) ;
let [ hours, minutes] = time. split ( ':' ) ;
if ( hours === '12' ) {
hours = '00' ;
}
if ( modifier === 'PM' ) {
hours = parseInt ( hours, 10 ) + 12 ;
hours = hours. toString ( ) . padStart ( 2 , '0' ) ;
}
return ` ${ hours} : ${ minutes} ` ;
}
console. log ( convertTo24Hour ( '01:30 PM' ) ) ;
console. log ( convertTo24Hour ( '12:30 AM' ) ) ;
console. log ( convertTo24Hour ( '11:59 PM' ) ) ;