Date Difference in IOS [closed] - ios

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I had Two Dates from date and to date. I stored two dates in NSString like string1 and string 2 respectively. Now My Problem is I want the difference of these two dates. My Date format is 04-Mar-2014 and 14-Mar-2014 and I want the result to be like 10.

You can get difference by using the code given below:-
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];
[f release];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
[gregorianCalendar release];
components now holds the difference.
NSLog(#"%ld", [components day]);
Courtesy:-vikingosegundo
https://stackoverflow.com/a/4576575/1865424

Three methods you need are:
+ (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YOUR_STRING_FORMAT"];
}
[NSTimeZone resetSystemTimeZone];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
return dateFormatter;
}
+ (NSDate *)dateWithString:(NSString *)dateString
{
return [[self dateFormatter] dateFromString:dateString];
}
- (NSInteger)distanceInDaysToDate:(NSDate *)date
{
NSDateComponents *components1 = [CURRENT_CALENDAR components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self];
components1.hour = 0;
components1.minute = 0;
components1.second = 0;
NSDateComponents *components2 = [CURRENT_CALENDAR components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
components1.hour = 0;
components1.minute = 0;
components1.second = 0;
NSDate *date1 = [CURRENT_CALENDAR dateFromComponents:components1];
NSDate *date2 = [CURRENT_CALENDAR dateFromComponents:components2];
NSDateComponents *components = [CURRENT_CALENDAR components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0];
return components.day;
}
Best if you move them into NSDate category.

You Two date is
NSString* str1 = #"04-Mar-2014";
NSString* str2 = #"14-Mar-2014";
Now convert two date in to DD-MM-YYY as below
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
Now string convert into date
NSDate *date1 = [dateFormat dateFromString:str1];
NSDate *date2 = [dateFormat dateFromString:str2];
Calculation of convert between two date
NSTimeInterval distanceBetweenDates = [date2 timeIntervalSinceDate:date1];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
NSInteger day = hoursBetweenDates/ 24;
Your OUTPUT : 10

I think, according to your question, my assumption is difference between two dates. You can use this.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
NSDate *date1 = [dateFormat dateFromString:#"04-Mar-2014"];
NSDate *date2 = [dateFormat dateFromString:#"14-Mar-2014"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
NSLog(#"There are %d days in between the two dates.", numberOfDays);

While keeping the NSDate objects is the best solution, you can recreate NSDateobjects from the string using an NSDateFormatter with its format string set accordingly to your date format.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MMM-yy"];
[dateFormatter dateFromString:yourString];
Then you can use for example the timerIntervalSinceDate:method of NSDateand calculate the difference. Alternatively you can extract NSDateComponentsand get the difference that way.

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 get NSDate start of previous month?

I suppose that I ask duplicate question, but I can not find solution for me. I need to get 1st day of the previous month. As I understand I have to get calendar from today, subtract 1 month and set day to be 1st. After that I have to convert to date. Unfortunately I get last day of previous month.
I use following code:
NSDate *maxDate = [[NSDate alloc] init];
NSCalendar *calendarCurr = [NSCalendar currentCalendar];
NSDateComponents *components = [calendarCurr components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:maxDate];
[components setMonth:-1];
components.day = 1;
NSDate *minDate = [calendarCurr dateFromComponents:components];
NSLog(#"%#", minDate);
EDIT:
Yes, it is duplicate, but answers in that question does not help me. I still get 30/09/2014 (when today is 17/11/2014) instead of 01/10/2014. I suppose that my problem is time of todays date.
Well, Here a new approach:
NSDate *today = [NSDate date];
NSDateFormatter *formatterYear = [[NSDateFormatter alloc] init];
[formatterYear setDateFormat:#"yyyy"];
NSDateFormatter *formatterMonth = [[NSDateFormatter alloc] init];
[formatterMonth setDateFormat:#"MM"];
[formatterMonth setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString *yearString = [formatterYear stringFromDate:today];
NSString *monthString = [formatterMonth stringFromDate:today];
NSInteger month,year;
if ([monthString integerValue] == 1) {
year = [yearString integerValue] -1;
month = 12;
} else
{
year = [yearString integerValue];
month = [monthString integerValue]-1;
}
NSDateFormatter *exitFormatter = [[NSDateFormatter alloc] init];
[exitFormatter setDateFormat:#"yyyy-MM-dd"];
[exitFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString *stringDate;
if (month < 10) {
stringDate = [NSString stringWithFormat:#"%ld-0%ld-01",(long)year,(long)month];
} else {
stringDate = [NSString stringWithFormat:#"%ld-%ld-01",(long)year,(long)month];
}
NSDate *firstDatePreviousMonth = [exitFormatter dateFromString:stringDate];
NSLog(#"View the date: %#",[firstDatePreviousMonth description]);
Wrong calculation.
Use this code to set Month component.
[components setMonth:components.month -1];
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
[dateFormatter1 setDateFormat:#"MM"];
NSString *stringCurrentDate = [dateFormatter1 stringFromDate:currentDate];
int monthInt= [stringCurrentDate intValue];
[dateFormatter1 setDateFormat:#"yyyy"];
NSString *dateString = [dateFormatter1 stringFromDate:currentDate];
int yearInt = [dateString intValue];
monthInt-= 1;
if (monthInt== 0) {
monthInt= 12;
yearInt -=1;
}
dateString = [NSString stringWithFormat:#"%#-01-%#",[#(monthInt)stringValue],[#(yearInt)stringValue]];
NSLog(#"this is previous month first date : %#",dateString);
run it as it is, obviously first day of month will be 01, so this is static here. your can change accordingly. happy coding
Try this:
NSDate *maxDate = [NSDate date];
NSCalendar *calendarCurr = [NSCalendar currentCalendar];
NSDateComponents *components = [calendarCurr components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitTimeZone | NSCalendarUnitSecond | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:maxDate];
[components setMonth:components.month - 1];
[components setDay:1];
NSDate *minDate = [calendarCurr dateFromComponents:components];
NSLog(#">>>>>>>>>>%#", minDate.description);

setting time when formatting date using NSDateformatter

I have following code to convert string to date. Is it possible that it sets time as "00:00:00" and not the current time?
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:#"yyyy-MM-dd"];
NSString *str = #"2014-08-08";
NSDate *dt = [dateformat dateFromString:str];
This gives dt as "2014-08-08 15:20:00 +0000" because I did the operation at 15:20.
Edit: I am using this date to convert it to integer later to store it in database:
int t = [dt timeIntervalSince1970];
If you are displaying the date dt with NSLog you will see what the date description method provides. If you want to see the date in a specific way that suits you use NSDateFormatter to format the date.
Example:
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:#"yyyy-MM-dd"];
NSString *str = #"2014-08-08";
NSDate *dt = [dateformat dateFromString:str];
NSDateFormatter *displayDateformat = [[NSDateFormatter alloc] init];
[displayDateformat setDateFormat:#"yyyy-MM-dd"];
NSString *displayDateString = [displayDateformat stringFromDate:dt];
NSLog(#"displayDateString: %#", displayDateString);
Output:
2014-08-08
Note per Apple docs: "This method returns a time value relative to an absolute reference dateā€”the first instant of 1 January 2001, GMT."
A good practice is to use NSDateComponents
NSDate *yourDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:yourDate];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
// Set the time components manually
[dateComponents setHour:0];
[dateComponents setMinute:0];
[dateComponents setSecond:0];
yourDate = [calendar dateFromComponents:dateComponents];
Update
iOS8 :
[[NSCalendar currentCalendar] startOfDayForDate:[NSDate date]];

UITableview title bar with date for week?

How can I have the title of UITableview with date?
I know I can edit the title using:
self.title=#"meals for ..";
I want to add the date for one week. How can I do that?
You can get a date like this:
NSDate *theDateToday = [NSDate date];
And format it like this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE MMM dd"];
NSString *theDateAsAString = [dateFormatter stringFromDate:theDateToday];
Combine that with what you have like this:
self.title = [NSString stringWithFormat:#"meals for %#", theDateAsAString];
As for finding the days of the week, you could try adapting this answer.
- (NSString *)getWeekStartDateAsString:(NSDate *)date {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:#"yyyy-MM-dd"];
dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];
weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain];
return weekstartPrev;
}
- (NSString *)getWeekEndDateAsString:(NSDate *)date {
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week
NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
[dateFormat_End setDateFormat:#"yyyy-MM-dd"];
dateEndPrev = [dateFormat stringFromDate:EndOfWeek];
weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain];
return weekEndPrev;
}
You end result might look like this:
self.title = [NSString stringWithFormat:#"meals for %#-%#", [self getWeekStartDateAsString:theDateToday], [self getWeekEndDateAsString:theDateToday]];
A rarely known NSCalendar method will be the best option IMO
rangeOfUnit:startDate:interval:forDate:. It gives you the start and the duration (interval) for a certain time unit. With it it is easy to find the start of the week in the used calendar and add the range-1 to get the latest second in that week.
With the also rarely seen localizedStringFromDate:dateStyle:timeStyle: Available in OS X v10.6, iOS 4.0 it is easy to create a localized representation of the dates.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSWeekCalendarUnit
startDate:&startOfTheWeek
interval:&interval
forDate:now];
//startOfWeek is 2013-06-02 22:00:00 +0000 now (note: it is GMT with timezone support for my timezone Europe/Berlin/DST)
endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1];
// 2013-06-09 21:59:59 +0000
NSString *text = [NSDateFormatter localizedStringFromDate:startOfTheWeek
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterNoStyle];
text = [text stringByAppendingString:#" to "];
text = [text stringByAppendingFormat:#"%#", [NSDateFormatter localizedStringFromDate:endOfWeek
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterNoStyle]];
self.title=text;
results in 03.06.13 to 09.06.13 for my german locale, where Monday is start of the week.

Resources