iOS) Date 로 날짜다루기
Date 로 날짜 다루기
Date()
를 저장해서 사용
.dateComponents
사용해봤다 하지만 역시 불편하다
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "StoryTVC") as? StoryTVC else {
return UITableViewCell()
}
let month = Calendar.current.dateComponents([.month], from: storyList[indexPath.row].date ?? Date()).month
let day = Calendar.current.dateComponents([.day], from: storyList[indexPath.row].date ?? Date()).day
var dayText = ""
if let month = month ,let day = day {
if month < 10 && day < 10 {
dayText = "0\(month).0\(day)"
} else if month < 10 && day >= 10 {
dayText = "0\(month).\(day)"
} else if month >= 10 && day < 10 {
dayText = "\(month).0\(day)"
} else {
dayText = "\(month).\(day)"
}
}
cell.setData(title: storyList[indexPath.row].title ?? "" , date: dayText)
return cell
}
let request: NSFetchRequest<StoryModel> = StoryModel.fetchRequest()
let fetchResult = PersistenceManager.shared.fetch(reqeust: request)
titleButton.setTitle(fetchResult[self.indexPath].title, for: .normal)
if let date = fetchResult[self.indexPath].date {
let year = Calendar.current.dateComponents([.year], from: date).year!
let month = Calendar.current.dateComponents([.month], from: date).month!
let day = Calendar.current.dateComponents([.day], from: date).day!
let week = Calendar.current.dateComponents([.weekday], from: date).weekday!
let hour = Calendar.current.dateComponents([.hour], from: date).hour!
let minute = Calendar.current.dateComponents([.minute], from: date).minute!
var pmam = ""
switch hour {
case 0..<12:
pmam = "오전"
break
case 12..<24:
pmam = "오후"
break
default:
break
}
var weekDay = ""
switch week {
case 1:
weekDay = "일"
break
case 2:
weekDay = "월"
break
case 3:
weekDay = "화"
break
case 4:
weekDay = "수"
break
case 5:
weekDay = "목"
break
case 6:
weekDay = "금"
break
case 7:
weekDay = "토"
break
default:
break
}
dateLabel.text = "\(year)년 \(month)월 \(day)일 \(weekDay) \(pmam) \(hour):\(minute)"
- 조금 더 편한 방법으로
DateFormatter.dateFormat()
를 사용해서 형식을 정해서 사용해보자.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "StoryTVC") as? StoryTVC else {
return UITableViewCell()
}
if let date = storyList[indexPath.row].date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM.dd"
dateFormatter.locale = Locale(identifier: "ko_KR")
let dateStr = dateFormatter.string(from: date)
cell.setData(title: storyList[indexPath.row].title ?? "" , date: dateStr)
}
return cell
}
if let date = fetchResult[self.indexPath].date {
// 2021년 6월 9일 수 오전 12:40
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy년 MM월 dd일 E a hh:mm"
dateFormatter.locale = Locale(identifier: "ko_KR")
let dateStr = dateFormatter.string(from: date)
dateLabel.text = dateStr
}
위의 방식처럼 Core Data 에 자료형 Date
를 사용해서 저장 후 추출해서 사용했다.