Date Time difference in minutes in ios [duplicate] - ios

This question already has answers here:
How to calculate time in hours between two dates in iOS
(5 answers)
Closed 6 years ago.
i am using following method to get date time difference in minutes it giving me negative value .
I am using following code :
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSUInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitMinute;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:dt2
toDate:dt1 options:0];
NSInteger months = [components month];
NSInteger days = [components day];
NSInteger minutes = [components minute];
NSLog(#"months %ld",(long)months);
NSLog(#"days %ld",(long)days);
NSLog(#"minutes %ld",(long)minutes);
int res = (int)minutes;
NSLog(#"int minutes %d",res);
return res;
I want to calculate difference between these two below date in minutes:
date1:2016-11-23 07:39:44 +0000
date2:2016-11-23 08:13:44 +0000
As a result I'm getting -34.

You need to replace with this :
NSDateComponents *components = [gregorian components:unitFlags
fromDate:dt1
toDate:dt2 options:0];

fromDate will contain an earlier date and toDate will contains later date in NSDateComponents you are passing it wrongly change this
NSDateComponents *components = [gregorian components:unitFlags
fromDate:dt2
toDate:dt1 options:0];
to this
NSDateComponents *components = [gregorian components:unitFlags
fromDate:dt1
toDate:dt2 options:0];

If you don't know which date is former, just return absolute value of difference. That will always give you positive value.
return abs(res);

Related

How to find Next Sunday in different Timezone (EST & IST)

I have to find next Sunday date (NSDate) from device's current date.
I have used below logic:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self];
NSUInteger weekdayToday = [components weekday];
NSInteger daysToMonday = (8 - weekdayToday) % 7;
NSDate *weekEndPrev = [self dateByAddingTimeInterval:60*60*24*daysToMonday];
Here, in EST if time is near to 11 PM, I'm getting Monday as Weekend.
Let me know feasible solution. I have tried many options. Nothings works with 2 different timezones.
Thanks in Advance.
You need just to get the number of days you need and then just add them to your current date:
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate * newDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:value toDate:date options:0];
where value - is the number of days to add
Find current week Sunday Date first then add 7 days using NSDateComponents.
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *weekdayComponents = [gregorian components:NSCalendarUnitWeekday fromDate:today];
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay:(0 - ([weekdayComponents weekday] - 1))];
NSDate *sudayCurWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:7];
NSDate *nextSunday = [gregorian dateByAddingComponents:offsetComponents toDate:sudayCurWeek options:0];
NSLog(#"%#",nextSunday);
You can do this without any math, which is best left to NSCalendar as it handles daylight savings etc. First you need a calendar with the correct time zone. For example for IST:
NSCalendar *gc = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
gc.timeZone = [NSTimeZone timeZoneWithName:#"IST"];
Then you can use nextDateAfterDate:matchingUnit:value:options: to find the start of the next Sunday after a given time. For example:
NSDate *start = ... // the time you wish to start from
NSDate *nextSunday =
[gc nextDateAfterDate:start
matching:UnitNSCalendarUnitWeekday // match based on weekday number
value:1 // Sunday = weekday 1
options:NSCalendarMatchNextTime // read the docs!
];
The returned date, nextSunday, will be the next Sunday at 00:00 in the timezone of the calendar, gc.
HTH
Finally, I got solution..
NSDateComponents *components = [[NSCalendar currentCalendar] componentsInTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"] fromDate:[NSDate date]]; // Pass date for which you want to find next Sunday
NSUInteger weekdayToday = [components weekday];
NSInteger daysToMonday = (8 - weekdayToday) % 7;
NSDate *weekEndPrev = [[NSDate date] dateByAddingTimeInterval:60*60*24*daysToMonday];

How to show time which is less than a day?

This code will return number of days between two days.
How to determine when time will pass and day become hours like (20 hours) or (40 minutes), then how do I check that it's a day or less than a day.
-(NSInteger)numberOfDaysUntilDay:(NSDate *)aDate
{
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitDay
fromDate:self
toDate:aDate options:kNilOptions];
return [components day];
}
Use NSCalendarUnitSecond instead.
NSDateComponents *components = [calendar components:NSCalendarUnitSecond
fromDate:date
toDate:aDate options:kNilOptions];
Later you can convert seconds to any unit (hour, day, year).

Elapsed days between two dates always giving one days difference

I'm trying to work out the number of days between two dates. Here is how I am doing it:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int calendarFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDate *dateToCheck = (self.subscriptionEnd ?: self.trialEnd);
NSLog(#"dateToCheck: %#", dateToCheck);
NSLog(#"current date: %#", [self systemTimeZoneDate]);
NSDateComponents *components = [gregorian components:calendarFlags
fromDate:[self systemTimeZoneDate]
toDate:dateToCheck
options:0];
return [components day] >= 0 ?: 0;
At the time of this writing, NSLog outputted the following:
2014-09-05 22:56:20.054 tweepy[9635:60b] dateToCheck: 2014-10-05 08:02:51 PM +0000
2014-09-05 22:56:20.057 tweepy[9635:60b] current date: 2014-09-05 10:56:20 PM +0000
It is returning a difference of one day because iOS thinks that the day is in YDM format.
Should I be indicating the date format somewhere?
Here is the code of how self.subscriptionEnd is setup:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = 30;
self.subscriptionEnd = [gregorianCalendar dateByAddingComponents:dateComponents toDate:[self systemTimeZoneDate] options:0];
Here is the code of how self.trialEnd is setup:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = 2;
self.trialEnd = [gregorian dateByAddingComponents:dateComponents toDate:[self systemTimeZoneDate] options:0];
The date format doesn't have anything to do with it. What is happening is the NSDateComponents are giving you what you are asking for, the total difference in years, months, and days. If you want just the days, you need to only provide NSDayCalendarUnit. The docs make this clear:
Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally larger components will be computed before smaller components; for example, in the Gregorian calendar a result might be 1 month and 5 days instead of, for example, 0 months and 35 days.

NSCalendar to get date difference between now and end of year gives a zero month

I'm getting a 0 for the month when I try to get the date difference from now and the end of the year. I'm using a NSCalendar object to get the difference between two NSDate objects.
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2013];
[comps setMonth:0];
[comps setDay:0];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *newDate = [calendar dateFromComponents:comps];
NSDateComponents *timeDifference = [[NSCalendar currentCalendar]
components: NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit |
NSMinuteCalendarUnit | NSSecondCalendarUnit
fromDate:[NSDate date] toDate:newDate options:0];
int months = timeDifference.month;
int days = timeDifference.day;
if (months>0)
days+=31;
int hours = timeDifference.hour;
int minutes = timeDifference.minute;
int seconds = timeDifference.second;
You're trying to calculate number of months, days, etc to year 2013. In NSDateComponents 0 means 'no value', all values that count should be greater than 0. That's why your comps value is considered as 'incomplete', which causes strange output from NSCalendar.
Set month and day in lines 3-4 to 1 fix the issue.

How to determine day, month, and year as int in iOS

I want to determine day, month, and year of current date in iOS. I found this after a search on the net:
NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit) fromDate:date];
NSInteger Day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
This code shows the day correct, but the year and month is not showing as it should be. It shows some digits like 2147483647. I could not find a solution so please help me correct the code I found, or write some new code which does what I need.
This line is the problem:
NSDateComponents *components = [calendar components:(NSDayCalendarUnit) fromDate:date];
It should be
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];

Resources