2015-01-22 4 views
2

날짜에서 주 번호를 얻으려고합니다. 이것은 단지에 상관없이 0을 반환하지 왜 사람이 어떤 일 내가 거기에 넣어 말해 주시겠습니까 :NSCalendar 주 날짜 날짜

let currentWeekNumber = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: myDate).weekOfYear 

MyDate가의 형식이 2015년 1월 23일 11시 52분 35초 0000

같다 스위프트의 솔루션은 좋을 것입니다 :)

+2

재생산 할 수 없습니다. 'let myDate = NSDate()'를 사용하면 코드가 올바른 값인'4'를 반환합니다. –

+0

입력 데이터가있는 자그마한 예제 (실제)와 예상 된 출력이 도움이 될 것입니다. –

+0

노력에 감사드립니다, 마틴. 어떻게 든 입력 날짜를 엉망으로 만들었습니다. – TommyF

답변

3

게시 된 라인과 같은 것으로는 오류가 없습니다. 결과가 같은지 확인하려면 아래의 솔루션을 확인하십시오.

참고 : 날짜로 인한 관련성없는 문제를 없애려하고 있습니다. Swift 용으로 사용할 수 있습니다.

Week: = 4 
+1

질문에있는 코드는 잘 작동해야합니다 ... –

+0

그냥 myDate에 오류가 있는지 확인하려고합니다. – bllakjakk

+1

죄송합니다, 얘들 아! 어떻게 든 입력 날짜를 엉망으로 만들었습니다. ( 솔루션은 잘 작동하는데, bllakjakk입니다. 그러므로 내 질문에서 내 한 줄자와 동일합니다.) Martin R – TommyF

0

사용이 코드

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitWeekOfMonth fromDate:[NSDate date]]; 
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSInteger month = [components month]; 
    NSInteger year = [components year]; 
    NSInteger day = [components day]; 
    NSLog(@"%ld",(long)[components weekOfMonth]); 
1

이 시도 :

let calender = NSCalendar.currentCalendar() 
let dateComponent = calender.components(NSCalendarUnit.WeekOfYearCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.YearCalendarUnit, fromDate:NSDate()) 

println ("Week: = \(dateComponent.weekOfYear)") 

따라서 응답은 다음과 같이해야한다

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitWeekOfMonth fromDate:[NSDate date]]; 
NSInteger curr_month = [components month]; 
NSInteger curr_year = [components year]; 
NSInteger curr_date = [components day]; 
NSLog(@"%d %d %d, \n Week no: %ld",curr_date, curr_month,curr_year, (long)[components weekOfMonth]); 

출력 것은 : 2015년 1월 22일 (18) : 19 : 40.209 샘플 [38734 : 3031191] 22 1 2015,

주 번호 : 4