HackerRank
[해커랭크] (1 Week Day 1) Time Conversion (javascript)
hee0
2022. 8. 21. 12:59
주어진 12시간제의 값을 24시간제로 변환
조건
- 12:00:00PM은 12시간제, 12:00:00은 24시간제 표기
제한사항
- 입력되는 시간은 모두 유효
나의 풀이
- 더 간결한 코드로 만들 수 있을 것으로 보임
- ':'로 구분하여 hh, mm, ss(+PM|AM)으로 파싱
- hh : 12시간제 시간
- mm: 분
- ss: 초
- HH: 24시간제 시간
- PM|AM에 여부에 따라 시간계산 처리
- PM
- hh 값이 12가 아닌경우 '12 + hh'
- AM
- hh 값이 12인 경우 '00'
- PM
// 생략
/*
* Complete the 'timeConversion' function below.
*
* The function is expected to return a STRING.
* The function accepts STRING s as parameter.
*/
function timeConversion(s) {
// Write your code here
const [hh, mm, ss] = s.split(':');
const pm = s.endsWith('PM');
const second = ss.match(/\d+/g)[0];
let HH = hh;
if (pm) {
if(hh !== '12') {
HH = 12 + +hh;
}
} else {
if (hh === '12') {
HH = '00';
}
}
return `${HH}:${mm}:${second}`;
}
// ...후략