How to get number of days between two dates objective-c [duplicate] - ios

This question already has answers here:
How can I compare two dates, return a number of days
(4 answers)
Calculating the number of days between two dates in Objective-C
(8 answers)
Closed 9 years ago.
I'm trying to make a label that says how many days left till event. I want to calculate the difference between todays date and the events date. I'm using this code and its giving me -4600. It works fine till I use todays date.
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd"];
NSDate *startDate = [NSDate date];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
return components.day;
return components.day;

By default [NSDate date] return date in like 2013-08-06 08:50:25 +0000
and you have set your formatter to yyyy-MM-dd this, so you have to convert your startDate to yyyy-MM-dd this form..
Try this
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-ddHH:mm:ss ZZZ"];
NSDate *startDate = [NSDate date];
NSLog(#"%#",startDate);
NSDate *endDate = [f dateFromString:end];
NSLog(#"%#",endDate);
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
return components.day;

Related

Finding the difference between two dates always prints 10

Following is my code to get current date.
-(NSString *) getCurrentDate {
NSDateFormatter *dateformater = [[NSDateFormatter alloc]init];
[dateformater setDateFormat:#"dd-MMM-yyyy"];
NSString *today=[dateformater stringFromDate:[NSDate date]];
return today;
}
Im using the following code to find the difference between current date and the date selected from pickerview
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MMM-yyyy"];
NSString *date = [dateFormat stringFromDate:picker.date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:GregorianCalendar];
NSCalendarUnit unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"dd-MMM-yyyy"];
NSDate *selectedDate = [f dateFromString:date];
NSDate *currentDate = [f dateFromString:[self getCurrentDate]];
NSDateComponents *currentDateComponent = [gregorianCalendar components:unitFlags fromDate:currentDate toDate:selectedDate options:0];
but the currentDateComponent.day always prints the value 10.
whats wrong with my code? how can i be able to find the difference between two dates?
I think components you are using is wrong it should but only NSCalendarUnitDay
My code is returning me correct difference (difference.day).
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:[NSDate date] toDate:enDate options:0];

How in iOS to get first date of the month? [duplicate]

This question already has an answer here:
NSDateFormatter - 1 day incorrect?
(1 answer)
Closed 7 years ago.
I try to get first date for the current month from [NSDate new]. My problem is that instead of 2015/06/01 I always receive 2015/05/31. I even try to convert string 20150601 to NSDate and I still receive 2015/05/31.
Here is my CODE (for the second element):
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyyMMdd"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
currentMonth = [dateFormatter dateFromString:#"20150601"];
The result is:
(lldb) print currentMonth
(__NSDate *) $0 = 0x79e64820 2015-05-31 21:00:00 UTC
EDIT:
Ok, I understand my mistake - I don't check correctly result of my operations. They always result in UTC.
10x, for answer and all comments. I will be more careful next time.
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone *zone = [NSTimeZone localTimeZone];
[formatter setTimeZone:zone];
[formatter setDateFormat:#"yyyyMMdd"];
NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
NSString *currentMonth = [formatter stringFromDate:dayOneInCurrentMonth];
NSLog(#"%#",currentMonth);
Output
2015-06-08 14:07:30.924 NSDATEDemo[1943:39838] 20150601
Create NSDateComponents from [NSDate date], set the current day to 1 and re-create your NSDate object:
- (NSDate *) dateAtStartOfMonth
{
//Not tested!!!
NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[comp setDay:1];
return [[NSCalendar currentCalendar] dateFromComponents:comp];
}

How to calculate days between two dates in ios. in between two dates [duplicate]

This question already has answers here:
Number of days between two NSDates [duplicate]
(16 answers)
Closed 8 years ago.
my question is to calculate days between two different dates in iOS.
to calculate how many days between two dates. i have to calculate 1990/02/05 to today date
how many days in between.
Try this:
NSString *start = #"2010-09-01";
NSString *end = #"2010-12-01";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
NSLog(#"%ld", [components day]);

Weird date result adding 1 month to a given date

I am using following piece of code to get next week date from a given date at 12:00am:
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit |NSHourCalendarUnit fromDate:now];
[components setHour:0];
NSDate *todayDate = [calendar dateFromComponents:components];
int daysToAdd = 7;
NSDate *tomorrowDate = [todayDate dateByAddingTimeInterval:60*60*24*daysToAdd];
NSString *stringDate = [NSString stringWithFormat:#"%#",tomorrowDate];
todoItemDueDateText.text = stringDate;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"EEEE, dd MMMM YYYY"];
NSString *fechasimulada = [dateFormatter stringFromDate:tomorrowDate];
dateFieldSimulatedText.text = fechasimulada;
If I log the result date, it is working fine.
Now, a similar piece of code to get next month date from a given date at 12:00am:
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:0];
NSDate *todayDate = [calendar dateFromComponents:components];
//NSDate *today = [NSDate date];
NSDateComponents* dateComponents = [[NSDateComponents alloc]init];
[dateComponents setMonth:1];
//NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* tomorrowDate = [calendar dateByAddingComponents:dateComponents toDate:todayDate options:0];
NSString *stringDate = [NSString stringWithFormat:#"%#",tomorrowDate];
todoItemDueDateText.text = stringDate;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"EEEE, dd MMMM YYYY"];
NSString *fechasimulada = [dateFormatter stringFromDate:tomorrowDate];
I don't know why, but the second piece of code gives the expected date but -1 hour.
UPDATE:
I will show you the dates:
Source date (today at 12:00am)+7 h
Next week date from previous given date:
Next month date from previous given date:
NSDate takes Daylight Savings into account. If you cross a DST day, you'll experience this issue.

Comparing NSDates Without Regard To Time [duplicate]

This question already has answers here:
Comparing two NSDates and ignoring the time component
(16 answers)
Closed 9 years ago.
Essentially I have a tip of the day feature, with specific tips associated with dates, and I need a way to compare the current NSDate to the saved date for the tip, regardless of time. Obviously the tip for January 1st is relevant at 10AM and 10:30, so I can't literally compare the NSDates. Here are some of the things I've tried:
Try 1 - Doesn't work
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
// [df setDateFormat:#"yyyy-MM-dd hh:mm:ss a"];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
Try 2 - Doesn't work
NSString * zoneString = [[NSString stringWithFormat:#"%i-%i-%iT00:00:00", year, month, day] substringFromIndex:([[NSString stringWithFormat:#"%i-%i-%iT00:00:00", year, month, day] length] - 5)];
NSTimeInterval timeInterval = [[zoneString substringToIndex:3] intValue] * 3600;
timeInterval += [[zoneString substringFromIndex:3] intValue] * 60;
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:timeInterval]];
[formatter setDateFormat:#"yyyy'-'MM'-'dd' 'HH':'mm':'ss ZZZ"];
NSLog(#"%#", [formatter stringFromDate:myDate]);
Try 3 - Doesn't work
NSDate *date = [NSDate date];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date interval:NULL forDate:date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
if ([[dateFormat stringFromDate:date] isEqualToString:[dateFormat stringFromDate:tipDate]])
As a rule of thumb, when you compare or manipulate NSDates, the right tool for the job is usually a combination of NSCalendar and NSDateComponents.
Use NSDateFormatter only when you need to format and display a NSDate.
With this in mind, NSDateComponents is the way to go, since you want to compare a subset of components from the two dates.
Create two NSDateComponents instances and compare them.
Example:
- (BOOL)isToday:(NSDate *)date {
NSDateComponents *todayComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:[NSDate date]];
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:date];
return [dateComponents isEqual:todayComponents];
}

Resources