How to get the 7 days previous date of current date? - iphone

I am working on a project where i need to set an alarm on 7 days before particular date the user has selected from date picker.
I used the following code to get the date from user
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterFullStyle];
NSString *dateStr = [NSString stringWithFormat:#"%#",[df stringFromDate:datePickerObj.date]];
[df release];
Can any one please tell me how to get the date of 7 days previous to the selected date.
Thanks in advance

Use dateByAddingComponents:toDate:options:, like this:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = -7;
NSDate *earlierDate = [calendar dateByAddingComponents:components
toDate:datePickerObj.date options:0];

Related

NSDate wrong output when add day to NSDate

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"%#",dateString);
// Retrieve NSDate instance from stringified date presentation
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
// Create and initialize date component instance
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:2];
// Retrieve date with increased days count
NSDate *newDate = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:dateFromString options:0];
NSLog(#"Original date: %#", [dateFormatter stringFromDate:dateFromString]);
NSLog(#"New date: %#", [dateFormatter stringFromDate:newDate]);
OutPut
2013-05-17
Original date: 2013-05-17
New date: 1412647-09-06
I add 2 day to that. The new date should be "2013-05-19?. Can anyone tell me what I wrong? Thank in advance.
I assume that you forgot to initialize the day variable. If you add
NSUInteger day = 2;
then your code produces the expected result in my test program.
The init methode of NSDateComponents does not initializes the components. Thus, e.g., year is undefined. Form Apple's documentation:
An instance of NSDateComponents is not responsible for answering questions about a date beyond the
information with which it was initialized. For example, if you initialize one with May 6, 2004,
its weekday is NSUndefinedDateComponent

Adding Month to NewDate

I am new to iPhone developer,
I made a one custom date in that custom date i want to add 1 month or 3 month or 6 month according to frequency.
i want to add month till newDate is less then today's date.
here is my code snippet,
while ([today compare:temp] == NSOrderedDescending)
{
NSLog(#"inside----- today=%#,temp=%#",today,temp);
//add to dates
NSDateComponents *newComponents= [[NSDateComponents alloc] init];
if([FrequencySelText isEqualToString:#"Monthly"]){
[newComponents setMonth:1];
}
if([FrequencySelText isEqualToString:#"Quarterly"]){
[newComponents setMonth:3];
}
if([FrequencySelText isEqualToString:#"Half - Yearly"]){
[newComponents setMonth:6];
}
if([FrequencySelText isEqualToString:#"Yearly"]){
[newComponents setMonth:12];
}
// get a new date by adding components
NSDate* temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSString *newDate = [formatter stringFromDate:temp];
NSLog(#"new date=%#",newDate);
}
My Log shows: inside----- today=2012-07-11 14:41:27 +0000,temp=2012-04-12 03:00:00 +0000
I am getting Exc_bad_access at this line, NSDate* temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0];
Any help will bw appreciated.
Providing value to temp again then no need provide NSDate object type again. Here u already have NSDate *temp then why r u using same name again for NSDate object
temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0]
Maybe try this one:
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[dateComponents setMonth:1]; // Sample Add
NSDate *tempDate = [gregorian dateByAddingComponents:dateComponents toDate: temp options:0];
NSString *strTempDate = [dateFormat stringFromDate:tempDate];
// New Date on strTempDate

writing logic Date difference - Newbie

Is there a way to subtract the current date by 5. say if today is 2008-12-9 i need to get the date 5 days back. If we output this, the date should display as 2008-12-4.
How can i code this programatically? or a tutorial that would help
Always use NSCalendar and NSDateComponents for date calculations. This will take into account oddities like leap years with 29 days in February, leap seconds and daylight saving changes.
NSDate *date = [NSDate date]; // Using current date here
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = - 5; // Find date for 5 days ago
NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];
Use NSDateComponents
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
[offsetComponents setDays:-5];
NSDate *fiveDaysAgo = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
to convert it to a string with the preferred format, use NSDateFormatter
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *formattedDateString = [dateFormatter stringFromDate:fiveDaysAgo];
This is the brute-force way:
Sustract 5 from DAY.
If DAY < 0, add number of days of the previous month and sustract 1 from MONTH.
If MONTH < 0, add number of month of a year and sustract 1 from YEAR.
The advantage of the brute-force approach is that it will work with every language.
#define SOME_HOUR -24*5
NSDate *today = [NSDate date];
NSDate *someDay = [NSDate dateWithTimeInterval:60*60*SOME_HOUR sinceDate:today];

How to find days between dates stored in 2 strings

I have two strings both are in following date format (2011-03-22).
i have to compare them and find number of days between them.
Can anyone tell me how to do this..
Please also tell me the correct method to convert them back to NSDate.
Might be a couple of errors as i just typed this, but it speaks for itself and you should get the idea.
NSString *dateStringA = #"2011-03-22";
NSString *dateStringB = #"2011-03-27";
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = #"yyyy-MM-dd";
NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates
NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them
 For string to date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];
for date to string
NSString *date = [[NSDate date] description];

Convert String to Date and fetch the difference

hi i have 2 dates in string format
base_date_string = 10-12-01 12:00:00
current_date_string = 10-12-23 10:18:00
both the above values are in string
i want to get the number of days elapsed between these 2 dates
I tried to convert them to NSDate using NSDateFormatters and then getting the difference.
I realised that string does not properly converts to NSDate
when i convert to nsdate i got
base_date:::2010-12-01 06:30:00 +0000
current_date::::2010-12-23 04:48:19 +0000 (the time portion is not perfect)
Formatter class that i used is:
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *base_date = [formatter1 dateFromString:#"10-12-01 12:00:00"];
[formatter1 release];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *current_date = [formatter2 dateFromString:current_date_string];
[formatter2 release];
//subrtrcation of basedate from current date to get elapsed number of days
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *diff = [calendar components:(NSDayCalendarUnit)
fromDate:base_date toDate:current_date options:0];
int date_value = [diff day];
Please any help is appreciated
30 seconds in the NSDate documentation revealed:
-[NSDate timeIntervalSinceDate:]
So using the dates in your question...
NSTimeInterval difference = [current_date timeIntervalSinceDate:base_date];
difference = fabs(difference);
NSLog(#"there are %f seconds between %# and %#", difference, current_date, base_date);
edit
ok, so the problem is not date differencing. You're observing that the string you're inputting is 5 and 1/2 hours ahead of the date you're getting back.
Well, let's look at this. The date returned is in GMT time (as denoted by the +0000). 5 and 1/2 hours ahead of that is the timezone used in India. So. Are you in India? If you are, then this is just a matter of needing to -setTimezone: on your NSDateFormatter.
You can use this code of function to get the difference between 2 dates
-(int)howManyDaysHavePast:(NSDate*)lastDate :(NSDate*)today {
NSDate *startDate = lastDate;
NSDate *endDate = today;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
[gregorian release];
int days = [components day];
return days;
}
hAPPY iCODING...
Use the following code
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *base_date = [formatter1 dateFromString:#"10-12-01 12:00:00"];
NSDate *current_date = [formatter2 dateFromString:current_date_string];
[formatter1 release];
NSTimeInterval difference = [current_date timeIntervalSinceDate:base_date];
Then you will get difference in number of seconds. Then you can get in number of days as following
float days = difference/86400;
The "days" consists the number of days that the current_date is differ from the base_date.