0

我正在做一些天气应用程序,因为我想显示 4 天的预报,即从当天到接下来的 3 天。我得到了今天,代码是

NSCalendar* cal = [NSCalendar currentCalendar];

NSDateComponents* comp = [cal components:NSWeekdayCalendarUnit fromDate:[NSDate date]];

 // 1 = Sunday, 2 = Monday, etc.

 NSInteger day0 = comp.weekday;

    NSLog(@"My DAY is %i", day0);


NSString *str;

NSMutableString *myString = [NSMutableString string];

str = [NSString stringWithFormat:@"%d",day0]; //%d or %i both is ok.

[myString appendString:str];

NSLog(@"My DAY is %@", myString);

输出为 6 即周五 .... 很酷

我怎样才能在不增加当天的情况下获得第二天...我试图增加当天,但问题是,如果我将当天的日期设为 7,它会增加到 8,在平日没有这样的事情对..我是xcode的新手..帮帮我....

4

2 回答 2

0

“我怎样才能在不增加当前日期的情况下获得第二天......”

如果你想要一个 NSDate 对象代表每一天,你可以使用 NSDateComponents 来加起来:

NSDate *today = [NSDate date];
NSDateComponents *offset = [[NSDateComponents alloc] init];
offset.day = 1; // create a one day offset
NSDate *tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:offset toDate:today options:0];

然后得到你的工作日:

[[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate:tomorrow];

“我试图增加当前日期,但问题是,如果我将当前日期设为 7,它会增加到 8,在平日没有这样的事情对..”

如果仅增加今天的工作日就足够了,请使用简单的模(这在任何编程语言中都是基本的):

int weekdayOfTomorrow = (++weekdayOfToday % 7) + 1;
于 2012-11-30T08:25:06.397 回答
0

尝试以下操作:

NSDateComponents *dayComponent = [NSDateComponents new];
dayComponent.day = 1;
today = [calendar dateByAddingComponents:dayComponent toDate:today options:0];
于 2012-11-30T08:23:29.100 回答