Changing the current date
I am working with the date in my iPhone development.开发者_如何学C I need to increase the date by 24 hours from the current date.
You can use dateByAddingTimeInterval
NSDate *currentDate = [NSDate date];
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)]; //one day
Simple:
NSDate *tomorrow = [[NSDate date] dateByAddingTimeInterval:86400];
you can add an NSTimeInterval. Since this is a double in seconds just add 24*60*60:
- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds
Try
NSDate *twentyFourHoursLater = [[NSDate alloc] initWithTimeIntervalSinceNow:60 * 60 * 24];
Save the download date in the NSUserdefaults then check if 24 hours have passed? If not notify the user that he/she will have to wait.
save the last download date in NSUserDefaults. And when you try to download just check for that date.
something like this:
- (BOOL)downloadDataForecedUpdate:(BOOL)forced {
NSDate *lastDownloadDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastDownloadDate"];
if (forced || !lastDownloadDate || [[NSDate date] timeIntervalSinceDate:lastDownloadDate] > 24 * 60 * 60) {
// start download
[NSURLConnection connectionWithRequest:myDownloadRequest delegate:self];
return YES;
}
return NO;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// process data
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"lastDownloadDate"];
}
you can call [self downloadDataForecedUpdate:NO]
whereever it is appropriate. on application launch or in an IBAction. Use the return value of the method to either show a download indicator or a alert that tells the user he has to wait more.
Depending on what you are really trying to achieve, just adding 86,400 (or 60 * 60 * 24 ) to your time interval might not be what you want. If for example, the user experiences a daylight-savings adjustment, then you will be off by an hour, or even a day if it happens near midnight. A better method is to ask the NSCalendar for the result, which takes into account the users local time zone.
NSDate *start = yourDate;
NSDateComponents *oneDay = [NSDateComponents new];
[oneDay setDay:1];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *end = [cal dateByAddingComponents:oneDay toDate:start options:0];
精彩评论