本文介绍了在iOS SDK中获取星期数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从日期中获取一年中的第几周.我按如下所示尝试了代码,但是给了我错误的第几周.

I want to get the Week number of the year from the date.I tried the code as follow but gives me a wrong week number.

我的第几周代码:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:@"2012-09-15"];


    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSLog(@"week: %i", [[calendar components: NSWeekOfYearCalendarUnit fromDate:date] weekOfYear]); //Display 38 instead of 37
}

注意:如果我尝试使用[NSDate date],则显示正确.

Note: If i try with with [NSDate date] display the correct.

帮我解决这个问题.谢谢

Help me to solve this..Thank you,

推荐答案

ObjectiveC:

ObjectiveC:

 NSCalendar *calendar = [NSCalendar currentCalendar];
 NSDateComponents *dateComponent = [calendar components:(NSWeekOfYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
 NSLog(@"%@",dateComponent);

更新

 NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:date];
    NSLog(@"%@",dateComponent);

迅速:

let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components([.WeekOfYear, .Day, .Month, .Year], fromDate: NSDate(timeIntervalSinceNow: 0))
print("weekOfYear \(dateComponent.weekOfYear)")

迅速3:

let component = Calendar.current.component(.weekOfYear, from: Date())
print("Week of Year \(component)")

这篇关于在iOS SDK中获取星期数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:30