2012-02-20 3 views
3

의 주 나는이 같은 날짜 형식, 날짜로부터는 NSString을 좀하고 싶습니다 :NSDateFormatter : 년 첫 평일

MMEEEY ww 

문제는 '전주', 올해의 주입니다. 백 오피스에서 가져온이 형식을 다른 형식과 비교해야합니다. 그러나 백 오피스의 첫 번째 평일은 월요일이고 iOS는 일요일입니다. 그래서, 일요일 일 때, 그 해의 주간은 같지 않기 때문에 문자열은 동일하지 않습니다.

질문 : NSDateFormatter가 월요일을 첫째 요일로 사용하도록하려면 어떻게해야합니까?

firstWeekday 속성을 2로 설정 한 달력을 사용하여 NSDateFormatter의 달력 속성을 설정하려고했지만 작동하지 않습니다. 이것의

요지 :

NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
calendar.firstWeekday = 2; 
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; 
dateFormatter.calendar = calendar; 

편집 : 노아의 대답 후 테스트

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; 
NSLocale * locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"]; 
dateFormatter.locale = locale; 
dateFormatter.dateFormat = @"MMEEEY ww"; 

NSDate * date = [NSDate dateWithTimeIntervalSince1970:1330251642]; // next sunday 

NSLog(@"%@ -> %@", date, [dateFormatter stringFromDate:date]); 

NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
calendar.firstWeekday = 2; 
dateFormatter.calendar = calendar; 

NSLog(@"%@ -> %@", date, [dateFormatter stringFromDate:date]); 

결과 : 몇 가지 테스트를 기반으로

2012-02-24 11:31:27.878 Test[2546:15203] 2012-02-26 10:20:42 +0000 -> 02Sun2012 09 
2012-02-24 11:31:27.880 Test[2546:15203] 2012-02-26 10:20:42 +0000 -> 02Sun2012 09 

답변

1

, 날짜 포맷이하는 달력 설정을 존중하는 것 같습니다. 어쩌면 형식을 지정하려는 날짜, 원하는 결과 및 얻는 결과에 대한 예제를 제공 할 수 있습니다.

NSDateFormatter * df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"MMEEEY ww"]; 

NSDate *date; 
date = [NSDate dateWithString:@"2012-01-01 12:00:00 +0000"]; 
NSLog(@"%@ -> %@", date, [df stringFromDate:date]); 

date = [NSDate dateWithString:@"2012-01-02 12:00:00 +0000"]; 
NSLog(@"%@ -> %@", date, [df stringFromDate:date]); 

NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
calendar.firstWeekday = 2; 
df.calendar = calendar; 

date = [NSDate dateWithString:@"2012-01-01 12:00:00 +0000"]; 
NSLog(@"%@ -> %@", date, [df stringFromDate:date]); 

date = [NSDate dateWithString:@"2012-01-02 12:00:00 +0000"]; 
NSLog(@"%@ -> %@", date, [df stringFromDate:date]); 

결과 :

2012-02-22 12:42:17.020 test[68385:207] 2012-01-01 12:00:00 +0000 -> 01Sun2012 01 
2012-02-22 12:42:17.021 test[68385:207] 2012-01-02 12:00:00 +0000 -> 01Mon2012 01 
2012-02-22 12:42:17.022 test[68385:207] 2012-01-01 12:00:00 +0000 -> 01Sun2011 52 
2012-02-22 12:42:17.022 test[68385:207] 2012-01-02 12:00:00 +0000 -> 01Mon2012 01 

나는 당신이 2011의 주 (52)의 1/1/12 부분을할지 모르겠어요,하지만 난 당신이 원하는 결과 부탁 해요 왜 다시, 그건.

+0

답변 해 주셔서 감사합니다. 나는 똑같이하려고 노력했지만 나에게 여전히 효과가 없다. 이유를 모르겠다. 어쨌든, 우리는 날짜 형식에서 주 번호를 사용하지 않기로 결정했다. 이상한 문제. – syfonseq