NSCalendar周日期

时间:2015-01-22 11:57:05

标签: ios swift nscalendar

我想从约会那里得到周数。有人可以告诉我为什么只有在我放入的那个日期才返回0:

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

myDate的格式如下:2015-01-23 11:52:35 +0000

Swift中的解决方案会很好:)

3 个答案:

答案 0 :(得分:3)

好像您的发布行没有错误。只需检查以下解决方案,确认结果是否相同。

注意:只是试图消除因日期而导致的任何无关问题。 对于Swift,您可以使用。

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

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

因此响应应如下所示:

Week: = 4

答案 1 :(得分:1)

试试这个:

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-01-22 18:19:40.209样本[38734:3031191] 22 1 2015,

周数:4

答案 2 :(得分: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]);