Changing the current date

2019-09-05 23:29发布

问题:

I am working with the date in my iPhone development. I need to increase the date by 24 hours from the current date.

回答1:

You can use dateByAddingTimeInterval

NSDate *currentDate = [NSDate date];
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)]; //one day


回答2:

Simple:

NSDate *tomorrow = [[NSDate date] dateByAddingTimeInterval:86400];


回答3:

you can add an NSTimeInterval. Since this is a double in seconds just add 24*60*60:

- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds


回答4:

Try

NSDate *twentyFourHoursLater = [[NSDate alloc] initWithTimeIntervalSinceNow:60 * 60 * 24];


回答5:

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.



回答6:

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.



回答7:

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