创建与NSString匹配的下一个NSDate [英] Create next NSDate that matches day NSString

查看:126
本文介绍了创建与NSString匹配的下一个NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个NSDate对象,表示第二天与NSString日匹配。

I would like to create an NSDate object that represents the next day that matches a NSString day.

例如。 NSString是MON或星期一我想获得与今天相匹配的下一个NSDate - 也可以是今天。

For example. The NSString is MON or Monday I want to get the next NSDate that matches this day - it can be today aswell.

例如:NSString day = @Tues;

e.g.: NSString day = @"Tues";

结果= 8月30日

推荐答案

NSInteger desiredWeekday = 3; // Tuesday

NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1;;

NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]];

NSInteger currentWeekday = dateComponents.weekday;
NSInteger differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek;

NSDateComponents *daysComponents = [[NSDateComponents alloc] init];
daysComponents.day = differenceDays;

NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:[NSDate date] options:0];

NSLog(@"newDate: %@", newDate);

2011-08-30 18:42:09.443测试[63789:707] newDate:2011-09 -05 22:42:09 +0000

2011-08-30 18:42:09.443 Test[63789:707] newDate: 2011-09-05 22:42:09 +0000

这篇关于创建与NSString匹配的下一个NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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