2014년 2월 26일 수요일

[iOS/OSX] NSDate로 상대 시간 구하기

NSDate 로 상대적인 시간 (예를 들어 D-day 처럼 지금부터 얼마의 시간이 남았나 등)을 계산해내려면 NSDate 클래스 만으론 불가능하고 NSCalendar를 이용해 계산해야 한다.

아래는 예제코드로 특정 NSDate 객체를 현재와 얼마나 차이(상대적 시간 차)가 있는지를 계산하는 코드이다.
NSDate *date = ...; // 현재 시간과 비교할 NSDate 객체
NSDate *now = [NSDate date];

NSCalendar *cal = [NSCalendar currentCalendar];
NSUInteger unit = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *comp = [cal components:unit
                                fromDate:now
                                  toDate:date
                                 options:0];
NSInteger day = comp.day;
NSInteger hour = comp.hour;
NSInteger min = comp.minute;
NSInteger sec = comp.second;

day, hour, min, sec 라는 심볼 이름만으로 쉽게 알 수가 있을 것이다.

필요하다면 unit을 확장해서 년이나 월 단위 계산도 가능하다.

사족. 개인적으로 NSDate 그리고 이와 연동되는 NSCalendar 라던가 NSDateComponents 의 존재는 Python을 좋아하는 사람으로써 참 불편하게 느껴진다. Python의 datetime.timedelta 같은 훌륭한 모델과 비교하자면 말이다.

댓글 없음 :