获取本月的每个 NSDate 作为 NSString [英] Getting every NSDate for this month as NSString

查看:52
本文介绍了获取本月的每个 NSDate 作为 NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我需要为一个月中的每一天存储一个 URL.从今往后.我该怎么做?

In my app i need to store a URL for every day of the month. From today and backwards. How would i do that?

到目前为止,将今天的 NSDate 作为 NSString 没有问题:

So far no problem getting todays NSDate as a NSString:

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

NSString* str = [format stringFromDate:date];

例如,如果我想要字符串中的日期,例如 17 天前,我将如何处理?

So how would i go about, for example, if i wanted the date in a string for, lets say, 17 days ago?

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

PS. i want to use these dates and store them in a string to fetch urls for every day for the past month, for example www.myurl.com/pictureYEAR-MONTH-DAY.jpg

推荐答案

这与 Alex 的回答类似,但看起来他只能从月初到今天的任何一天获得几天.以下是获取本月所有天数的方法:

This is similar to Alex's answer, but it looks like his only gets days from the start of the month to whatever day it is today. Here's how you can get all of the days this month:

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];
}

这将留下 NSDatesNSArray,即当月每天一个日期.

This will leave with with an NSArray of NSDates, with one date per day in the current month.

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

If you want a date that's "17 days ago", you can do that pretty easily too:

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

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

<小时>

一旦你有了一个 NSDate,把它变成一个字符串就很简单了:


Once you have an NSDate, it's pretty simple to turn it into a string:

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

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

这篇关于获取本月的每个 NSDate 作为 NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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