首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何从一周内获得NSDates?如果我知道weekOfMonth的话

问我如何从一周内获得NSDates?如果我知道weekOfMonth的话
EN

Stack Overflow用户
提问于 2016-02-02 21:42:35
回答 1查看 37关注 0票数 0

我需要知道NSDate在哪一周出现。我知道weekOfMonth,month和year。

例如,如果我的weekOfMonth是0,month是2,year是2016。我想获取当前周(从周日到周六)的可用日期。但由于本周的第一天(星期日)正好是上个月,我需要获取2016年2月1日到2016年2月6日(星期一到星期六)的日期。

代码语言:javascript
复制
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.month = components.month;
comp.year = components.year;
comp.day = ??; // What should I give here to get the current start date of the week?

或者,如果我能知道本周的开始日期和结束日期,那也会很有帮助。

EN

回答 1

Stack Overflow用户

发布于 2016-02-03 07:25:23

下面是一种略显笨拙的方法,它基于使用dayOfWeek = 0获取日期,然后继续前进,直到结果日期在同一个月内

代码语言:javascript
复制
int monthTarget = 2;
int dayOfWeekTarget = 0;
int yearTarget = 2016;

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setMonth:monthTarget];
[comp setYear:yearTarget];
[comp setWeekOfMonth:dayOfWeekTarget];

[comp setDay:dayOfWeekTarget];

// see what this gives us
NSDate *firstDate = [calendar dateFromComponents:comp];

NSDateComponents *firstDayComponents = [calendar components:NSCalendarUnitMonth |  NSCalendarUnitDay fromDate:firstDate];

NSInteger day = [firstDayComponents day];
NSInteger month = [firstDayComponents month];

// move forward if we have to
while (month < monthTarget)
{
    dayOfWeekTarget++;
    [comp setDay:dayOfWeekTarget];

    firstDate = [calendar dateFromComponents:comp];

    firstDayComponents = [calendar components:NSCalendarUnitMonth |  NSCalendarUnitDay fromDate:firstDate];

    day = [firstDayComponents day];
    month = [firstDayComponents month];
}

我相信您可以稍微整理一下,但是方法就在这里!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35155135

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档