134月/10
NSDateのTips
COCOA開発で日付の処理はよくある事です。
今日はいくつかの個人的Tipを共有します。
1. 日付間の日数を計算
#define TIME_INTERVAL_FOR_DAY 86400
// Calculate and return number of days between two dates.
+ (int) numberOfDaysBetween:(NSDate*)firstDate and:(NSDate*)secondDate {
NSTimeInterval interval = [secondDate timeIntervalSinceDate:firstDate];
// Add 1 for correct number of days
return (((int)interval) / TIME_INTERVAL_FOR_DAY)+1;
}
2. 日付に月を加算
//Add Month from Date
+ (NSDate *) date:(NSDate *)fromDate byAddingMonth:(int)monthOffset
{
NSDateComponents *month = [[NSDateComponents alloc] init];
[month setMonth:monthOffset];
NSDate *monthStartDateWithOffset =
[[NSCalendar currentCalendar] dateByAddingComponents:month toDate:fromDate options:0];
[month release];
return monthStartDateWithOffset;
}
3. 日付から一日のデータ取得
iPhoneの開発でデータを日付で絞って取得することはよくある処理でしょう。
※下記のソースはiPhone SDKでcore dataを使った場合です
- (NSArray *)dailyDataFromDate:(NSDate *)from_date {
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
//①
NSDateComponents *initComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:from_date];
//②
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
[componentsToSubtract setDay:+1];
NSDate *fromDate = [calendar dateFromComponents:initComponents];
NSDate *toDate = [calendar dateByAddingComponents: componentsToAdd toDate:fromDate options:0];
NSPredicate *requestPredicate = [NSPredicate predicateWithFormat:@"(timeStamp >= %@ ) and (timeStamp < %@)",fromDate,toDate];
//③
NSArray *matchingFetchedObjects = [fetchedResultsController.fetchedObjects filteredArrayUsingPredicate:requestPredicate];
[calendar release];
[componentsToSubtract release];
return matchingFetchedObjects;
}
まず、①は日付の時刻を初期化するコンポーネントを生成して一日の始発時間を取ります。
②では一日を追加するコンポーネントを生成します。
③でArrayに①と②で取得した日付をフィルタリングを掛けてデータを取得します。
アップルのサイトを参考
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtDates.html