[英]How to get the next day based on current day using NSCalendar
我正在做一些天气应用程序,因为我想显示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的新手。帮帮我...
尝试以下方法:
NSDateComponents *dayComponent = [NSDateComponents new];
dayComponent.day = 1;
today = [calendar dateByAddingComponents:dayComponent toDate:today options: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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.