将本月的每个NSDate都作为NSString获取

时间:2011-12-14 08:38:00

标签: objective-c ios

在我的应用中,我需要存储每月每天的网址。从今天开始,倒退。我该怎么做?

到目前为止,将NSDate作为NSString获取是没有问题的:

NSDate* date = [NSDate date];
NSDateFormatter* format = [[[NSDateFormatter alloc]init]autorelease];
[format setDateFormat:@"yyyyMdd"];

NSString* str = [format stringFromDate:date];

那么我怎么会这样做,例如,如果我想要一个字符串中的日期,比如17天前呢?

PS。我想使用这些日期并将它们存储在一个字符串中以获取过去一个月中每天的网址,例如www.myurl.com/pictureYEAR-MONTH-DAY.jpg

2 个答案:

答案 0 :(得分:6)

只需获取当前日期的NSDateComponents,然后从中提取日期,并编写一个for循环从中减去直到达到1,每次从组件创建新日期并更改日期,并将其存储为字符串。

代码可能说的不仅仅是单词,所以你去(测试):

NSMutableArray *dates = [[NSMutableArray alloc] init];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"yyyy-MM-dd"]; // you can set this to whatever you like
NSDate *today = [NSDate date]; // get todays date
NSCalendar *cal = [NSCalendar currentCalendar]; // needed to work with components
NSDateComponents *components = [cal components:(NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit) fromDate:today];
NSUInteger day = [components day];
for (NSUInteger i=day; i>0; i--) {
    // loop through all days till down to 1
    [components setDay:i]; // update the day in the components
    NSDate *date = [cal dateFromComponents:components]; 
    [dates addObject:[fmt stringFromDate:date]]; // add the new date
}

for (NSString *date in dates) {
    NSString *str = [NSString stringWithFormat:@"www.myurl.com/picture/%@",date];
    NSLog(@"%@",str); // voila, your URL.
}

[fmt release];
[dates release];

答案 1 :(得分:5)

这与亚历克斯的答案相似,但看起来他只能从月初到现在的任何一天都有几天。以下是您如何获得本月的所有日子:

NSDate *today = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];

NSMutableArray *datesThisMonth = [NSMutableArray array];
NSRange rangeOfDaysThisMonth = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:today];

NSDateComponents *components = [cal components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSEraCalendarUnit) fromDate:today];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];

for (NSInteger i = rangeOfDaysThisMonth.location; i < NSMaxRange(rangeOfDaysThisMonth); ++i) {
  [components setDay:i];
  NSDate *dayInMonth = [cal dateFromComponents:components];
  [datesThisMonth addObject:dayInMonth];
}

这将与NSArray NSDates保持一致,当月每天有一个日期。


如果你想要一个“17天前”的日期,你也可以很容易地做到这一点:

NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *diff = [[NSDateComponents alloc] init];
[diff setDay:-17];

NSDate *seventeenDaysAgo = [cal dateByAddingComponents:diff toDate:today];

获得NSDate之后,将其变为字符串非常简单:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];

NSDate *date = ...;
NSString *string = [formatter stringFromDate:date];