开发者

How to get future dates

开发者 https://www.devze.com 2023-04-08 10:57 出处:网络
How to get a few future dates开发者_如何转开发 with Wednesdays and Fridays using NSDateComponents? Answers will be greatly appreciated. Thanks in advance.This is actually a bit of a tricky problem if

How to get a few future dates开发者_如何转开发 with Wednesdays and Fridays using NSDateComponents? Answers will be greatly appreciated. Thanks in advance.


This is actually a bit of a tricky problem if you want it to be totally bullet-proof. Here's how I would do it:

NSInteger wednesday = 4; // Wed is the 4th day of the week (Sunday is 1)
NSInteger friday = 6;

NSDate *start = ...; // your starting date
NSDateComponents *components = [[NSDateComponents alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

for (int i = 0; i < 100; ++i) {
  [components setDay:i];
  NSDate *target = [gregorian dateByAddingComponents:components toDate:start options:0];
  NSDateComponents *targetComponents = [gregorian components:NSUIntegerMax fromDate:target];
  if ([targetComponents weekday] == wednesday || [targetComponents weekday] == friday) {
    NSLog(@"found wed/fri on %d-%d-%d", [targetComponents month], [targetComponents day], [targetComponents year]);
  }
}

[gregorian release];
[components release];


To get the correct day of the week, you must create a suitable instance of NSCalendar, create an NSDate object using dateFromComponents: and then use components:fromDate: to retrieve the weekday.


If you have NSDate instance for concrete weekday (f.e. Wednesday), you can get new future dates by using following code:

NSDate *yourDate = ...
NSDateComponents* components = [[NSDateComponents alloc] init];
components.week = weeks;
NSDate* futureDate = [[NSCalendar reCurrentCalendar] dateByAddingComponents:components toDate:yourDate options:0];
[components release];

P.S. Agree with Brian, try researching before asking.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号