如何在今天的一周内获得目标c

时间:2015-10-14 10:39:51

标签: ios objective-c nsdate nsdatecomponents

我试图在参考他们的约会时获得一周的日子。 例如:10月14日是星期三。 我正在创建一个集合视图单元格并显示如下日期。 various websites

在第14个单元格中,它将显示在星期三,但如何在第二天,星期四,星期五......等等。

我今天有日期,哪一天如下,

day = [components day];
week = [components month];
year = [components year];
weekday = [components weekday];
NSString *string = [NSString stringWithFormat:@"%ld.%ld.%ld", (long)day, (long)week, (long)year];
NSLog(@"%@",string);
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
NSLog(@"Today formatted date is %@",convertedDateString);

我已经在网上找到了这个方法,当你传递整数时,它返回字符串中的天数,但是我也遇到了麻烦,不知道每次传递哪个整数,所以我得到不同的字符串。

static inline NSString *stringFromWeekday(int weekday){
static NSString *strings[] = {
    @"Sunday",
    @"Monday",
    @"Tuesday",
    @"Wednesday",
    @"Thursday",
    @"Friday",
    @"Saturday",
};

return strings[weekday];

}

2 个答案:

答案 0 :(得分:6)

你已经掌握了一切。您应该在convertedDateString字符串中获取正确的日期名称。您只需要为todayDate对象添加24小时,然后再次使用dateformatter来获取第二天。

NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in

你可以在第二天这样做。

NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:(NSDayCalendarUnit | NSMonthCalenderUnit | NSYearCalenderUnit | NSWeekdayCalendarUnit) fromDate:today];
[dateComponents setDay:dateComponents.day+1];
NSDate *nextDay = [dateComponents date];
// Get the day by following same approach in the top

答案 1 :(得分:0)

从今天起,您将使用以下代码获得一周内的日子。

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
                [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];