Algorithm/HackerRank
[Warm Up] Time Conversion
SamusesApple
2023. 5. 11. 14:43
728x90
문제 설명:
Given a time in -hour AM/PM format, convert it to military (24-hour) time.
Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
- 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.
Example
* s = '12:01:00 PM'
Return '12:01:00'.
* s = '12:01:00 AM'
Return '00:01:00'.
내 풀이:
func timeConversion(s: String) -> String {
// Foundation에 dateFormatter 있으므로 활용
var timeFormatter = DateFormatter()
timeFormatter.dateFormat = "h:mm:ssa"
// Date 타입으로 변경
let date = timeFormatter.date(from: s)
// AM PM 없애기 위해 새로운 format 적용
timeFormatter.dateFormat = "HH:mm:ss"
// 변경된 format 적용된 date의 문자열 반환
return timeFormatter.string(from: date!)
}
회고:
Foundation 프레임워크에 DateFormatter가 있다는 것을 인지하고 있어, 간단하게 풀 수 있었다.
728x90