How to get the sample code of N days before and after the current date in IOS



I remember watching a cartoon about robot before. I forgot the specific name. But there is a line I remember very clearly

Today next year is your death day.

In connection with IOS, if you encounter the problem of calculating the date in the project, and you want to get the date n days after the current time (specified date), how can this be realized?

For example, if we want to get the date 7 days after the current date, how can we achieve it

Get current date

NSDate *currentDate = [NSDate date];

Time of day before or after

NSDate *lastDay = [NSDate dateWithTim eInterval:-24 *60*60  sinceDate:date ]; // the day before
NSDate *nextDay = [NSDate dateWithTim eInterval:24 *60*60  sinceDate:date ]; // day after
NSDictionary * timeDic = @{@"beginTime":[Utility timeStringFromFormat:@"yyyy-MM-dd" withDate:lastDay],@"endTime":[Utility timeStringFromFormat:@"yyyy-MM-dd" withDate:nextDay]};

Get the date after 7 days

Int days = 7; // days after n days
Nsdate * appointdate; // specifies the date declaration
Nstimeinterval oneday = 24 * 60 * 60; // how many seconds are there in a day
appointDate = [currentDate initWithTimeIntervalSinceNow: appointDate * days];

In this way, the date 7 days after the current date is obtained.

Similarly, you can also get the date 7 days before the current date, just add – to the last code.

appointDate = [currentDate initWithTimeIntervalSinceNow: -(appointDate * days)];

It’s so simple.

Similarly, we can also get the date n days after the specified date. Just replace the current date in the above code.


The above is the whole content of this article, I hope the content of this article has a certain reference value for your study or work, if you have any questions, you can leave a message to exchange, thank you for your support for developer.

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]