检查NSDate是在本周还是在下周 [英] Check if NSDate is in this week or next week

查看:49
本文介绍了检查NSDate是在本周还是在下周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以检查NSDate是本周还是下周?

there is a way to check if an NSDate is this week or is next week?

我知道今天是

[NSDate date]

那我该怎么办?

推荐答案

使用NSDateComponents,如下所示:

Use NSDateComponents, something like this:

NSCalendar *gregorian = [[NSCalendar alloc]
    initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *today = [NSDate date];

    NSDateComponents *todaysComponents =
        [gregorian components:NSWeekCalendarUnit fromDate:date];

    NSUInteger todaysWeek = [todaysComponents week];


    NSDate *anotherDate = [NSDate date];

    NSDateComponents *otherComponents =
        [gregorian components:NSWeekCalendarUnit fromDate:anotherDate];

    NSUInteger anotherWeek = [otherComponents week];

    if(todaysWeek==anotherWeek){
         NSLog(@"another date is this week");
    }else if(todaysWeek+1==anotherWeek){
         NSLog(@"another date is next week")
    }

您也可以使用其他组件(例如月份或年份)来完全确定.

You can also use other components like month or year to be completely sure.

注意:不要使用timeIntervals .通过使用NSDateComponents,您可以忽略小时,分钟和秒.我想你想要那个.

NOTE: Don't use timeIntervals. By using NSDateComponents you ignore the hour, minutes and seconds. I think you want that.

这篇关于检查NSDate是在本周还是在下周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆