🍏/iOS
[iOS] DateFormat > Hour > hh / h / HH / H 차이
eungding
2021. 7. 5. 16:10
728x90
반응형
Time Format 중 Hour를 헷갈렸어서 정리
[ 요약 ]
- HH: 24 hour format / 무조건 2자리 (필요할 경우, 앞에 0 붙여줌)
- hh : 12 hour format / 무조건 2자리 (필요할 경우, 앞에 0 붙여줌)
- H : 24 hour format / 1~2 자리
- h: 12 hour format / 1~2 자리
[ 실험 ]
우선 플레이그라운드를 열고 준비를 합니다.
Case 1.
let sampleDate = date(year: 2021, month: 7, day: 5, hour: 22, minute: 30)!
print(DateFormatter.time_HHmm.string(from: sampleDate)) // 22:30
print(DateFormatter.time_hhmm.string(from: sampleDate)) // 10:30
print(DateFormatter.time_Hmm.string(from: sampleDate)) // 22:30
print(DateFormatter.time_hmm.string(from: sampleDate)) // 10:30
Case 2.
let sampleDate = date(year: 2021, month: 7, day: 5, hour: 3, minute: 3)!
print(DateFormatter.time_HHmm.string(from: sampleDate)) // 03:03
print(DateFormatter.time_hhmm.string(from: sampleDate)) // 03:03
print(DateFormatter.time_Hmm.string(from: sampleDate)) // 3:03
print(DateFormatter.time_hmm.string(from: sampleDate)) // 3:03
[ 참고 ]
참고로 AM/PM or am/pm 표현은 a 이다.
12 hour format에서 07:05:45PM 은 hh:mm:ssa 로 나타낼 수 있다.
24 hour format 에서 19:05:45PM 은 HH:mm:ssa 로 나타낼 수 있다.
func timeConversion(s: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ssa"
let date = dateFormatter.date(from: s)
dateFormatter.dateFormat = "HH:mm:ssa"
return dateFormatter.string(from: date ?? Date())
}
// 12시간 포맷을 24시간 포맷으로 바꾸고 싶을 때
timeConversion(s: "07:05:45PM") // 19:05:45PM
func timeConversion(s: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ssa"
let date = dateFormatter.date(from: s)
dateFormatter.dateFormat = "hh:mm:ss a"
return dateFormatter.string(from: date ?? Date())
}
// PM을 한칸 띄우고 싶을 때
timeConversion(s: "07:05:45PM") // 07:05:45 PM
반응형