티스토리 뷰

Mobile/iOS

[iOS] NSDateFormatter 이용

out of coding 2016. 8. 4. 17:30

뭐 물론 그렇지만, 프로그램을 짤때는 시간같은것들을 많이 사용하게 된다.

간략하게 예를 들겠음.


NSDate *now = [NSDate date];


NSDateFormatter *defaultFormatter = [[NSDateFormatter alloc] init];

defaultFormatter.dateStyle = NSDateFormatterShortStyle;

defaultFormatter.timeStyle = NSDateFormatterShortStyle;


// 현재 시간을 시간 문자열로 변환

NSString *dateString = [defaultFormatter stringFromDate:now];


//문자열을 다시 NSDate로 변환

NSDate *parsedDate = [defaultFormatter dateFromString:dateString];


NSLog(@"Date : %@", now);

NSLog(@"dataString : %@", dateString);

NSLog(@"parsedData : %@", parsedDate);


대략 이런 방식으로 사용하면 되고, 정의된 방식을 이용하려면 다음과 같은 옵션들이 존재한다.


// “11/23/37” or “3:30pm”.

dateFormatter.dateStyle = NSDateFormatterShortStyle;

dateFormatter.timeStyle = NSDateFormatterShortStyle;


// “Nov 23, 1937” or “3:30pm”.

dateFormatter.dateStyle = NSDateFormatterMediumStyle;

dateFormatter.timeStyle = NSDateFormatterMediumStyle;


// “November 23, 1937” or “3:30:32pm”.

dateFormatter.dateStyle = NSDateFormatterLongStyle;

dateFormatter.timeStyle = NSDateFormatterLongStyle;


// “Tuesday, April 12, 1952 AD” or “3:30:42pm PST”.

dateFormatter.dateStyle = NSDateFormatterFullStyle;

dateFormatter.timeStyle = NSDateFormatterFullStyle;


형식을 자신이 주고 표현을 할 수도 있다.


NSDate *now = [NSDate date];


static NSDateFormatter *dateFormatter = nil;

if ( dateFormatter == nil ) {

dateFormatter = [[NSDateFormatter alloc] init];

NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[dateFormatter setLocale:enUSPOSIXLocale];

[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];

[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

}


NSString *rfc3339DateTimeString = [dateFormatter stringFromDate:now];

NSDate   *rfc3339DateTimeStringDate = [dateFormatter dateFromString:rfc3339DateTimeString];


NSLog(@"rfc3339   : %@", rfc3339DateTimeString);

NSLog(@"converted : %@", rfc3339DateTimeStringDate);


포멧 방식 확인.


http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns


'Mobile > iOS' 카테고리의 다른 글

[iOS] StickyTableView  (0) 2016.09.05
[iOS] Swift base project에 bridge 개발  (0) 2016.08.16
[iOS] 코드에서 ViewController 호출  (0) 2016.08.03
[iOS] UIViewController lifeCycle  (0) 2016.08.02
[iOS] Image Resize  (0) 2016.08.01
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함