有没有办法做到这一点?到目前为止,这是我的骨架:
@interface Daterange : NSObject{ NSDate startDate; NSDate endDate;}@property (nonatomic,retain) NSDate * startDate;@property (nonatomic,retain) NSDate * endDate;+ (Daterange *)rangeForDayContainingDate:(NSDate *)date;+ (Daterange *)rangeForWeekContainingDate:(NSDate *)date;+ (Daterange *)rangeForMonthContainingDate:(NSDate *)date;+ (Daterange *)rangeForYearContainingDate:(NSDate *)date;@end
一些示例用例如下:
Daterange * thisWeek = [Daterange rangeForWeekContainingDate:[NSDate date]];Daterange * thisYear = [Daterange rangeForYearContainingDate:[NSDate date]];
基本上,我希望返回的Daterange对象包含目标日期周围的周,月或年的开始和结束日期.例如(伪代码):
NSDate * today = [August 25,2009];Daterange * thisWeek = [Daterange rangeForWeekContainingDate:today];assert(thisWeek.startDate == [August 23,3009]);assert(thisWeek.endDate == [August 29,3009]);
更新:
由于answer provided by Kendall Helmstetter Geln,我能够完成这项工作.以下是一周范围内的完整方法:
+ (Daterange *)rangeForWeekContainingDate:(NSDate *)date{ Daterange * range = [[self alloc] init]; // start of the week NSDate * firstDay; [[self calendar] rangeOfUnit:NSWeekCalendarUnit startDate:&firstDay interval:0 forDate:date]; [range setStartDate:firstDay]; // end of the week NSDateComponents * oneWeek = [[NSDateComponents alloc] init]; [oneWeek setWeek:1]; [range setEndDate:[[self calendar] dateByAddingComponents:oneWeek toDate:firstDay options:0]]; [oneWeek release]; return [range autorelease];}解决方法 好吧,因为timeInterval是以秒为单位,所以只需要计算出一天中的秒数:
60秒* 60分钟* 24小时= 1天.
然后在rangeForDayContainingDate方法中,您可以提取日期组件,获取当前日期,根据设置为0:00的小时和分钟的日期创建新日期,并创建结束日期,添加上面计算的时间间隔.
总结以上是内存溢出为你收集整理的cocoa – 如何根据给定的NSDate生成方便的日期范围?全部内容,希望文章能够帮你解决cocoa – 如何根据给定的NSDate生成方便的日期范围?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)