2014-03-31 179 views
0

我正在嘗試創建一個函數,該函數僅提取具有特定日期的時間戳的數據。這是一個項目,最新的數據是從二月份開始的。我仍然希望使用昨天,上週,上個月的標準參數。嘗試將當前日期和日期參數設置爲過去日期

是否有任何方法將「當前日期」設置爲特定日期,以便我可以根據該日期而不是實際當前日期來設定時間範圍?

這是我已經試過

NSString *datestr = @"2014-02-16T04:59:50.021Z"; 
NSDateFormatter *dformat = [[NSDateFormatter alloc]init]; 

[dformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"]; 

NSDate *date = [dformat dateFromString:datestr]; 

NSTimeInterval secondsPerDay = 24 * 60 * 60; 

NSDate *yesterday = [[NSDate date] dateByAddingTimeInterval: date -secondsPerDay]; 
NSDate *lastWeek = [[NSDate alloc]initWithTimeIntervalSinceNow: - secondsPerDay * 7]; 
NSDate *lastMonth = [[NSDate alloc]initWithTimeIntervalSinceNow:-secondsPerDay * 30]; 

試圖減去secondsPerDaydate產生算術錯誤。任何解決方法?

回答

1

您不能從NSDate(這是一個對象)中減去NSTimeInterval(這是double)。你想發送的dateByAddingTimeInterval:消息從該時間將被減去日期:

NSString *datestr = @"2014-02-16T04:59:50.021Z"; 
NSDateFormatter *dformat = [[NSDateFormatter alloc]init]; 

[dformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"]; 

NSDate *date = [dformat dateFromString:datestr]; 

NSTimeInterval secondsPerDay = 24 * 60 * 60; 

NSDate *yesterday = [date dateByAddingTimeInterval:-secondsPerDay]; 
NSDate *lastWeek = [date dateByAddingTimeInterval:-(secondsPerDay * 7)]; 
NSDate *lastMonth = [date dateByAddingTimeInterval:-(secondsPerDay * 30)]; 

但是請注意,這lastMonth不會是完全正確的,因爲不是每個月份有30天。相反,你可能也想看看NSDateComponents

NSCalendar *calendar = [NSCalendar currentCalendar]; 

NSDateComponents *todayComponents = [NSDateComponents new]; 
todayComponents.year = 2014; 
todayComponents.month = 2; 
todayComponents.day = 16; 
todayComponents.hour = 4; 
todayComponents.minute = 59; 
todayComponents.second = 50; 

NSDate *today = [calendar dateFromComponents:todayComponents]; 

NSDateComponents *offset = [NSDateComponents new]; 
offset.day = -1; 
NSDate *yesterday = [calendar dateByAddingComponents:offset toDate:today options:0]; 

offset = [NSDateComponents new]; 
offset.day = -7; 
NSDate *lastWeek = [calendar dateByAddingComponents:offset toDate:today options:0]; 

offset = [NSDateComponents new]; 
offset.month = -1; 
NSDate *lastMonth = [calendar dateByAddingComponents:offset toDate:today options:0]; 
相關問題