I'm trying to get an NSMutableArray of NSDates each NSDate object targets the nearest rounded either HH:00 or HH:30 for the next 24 hours from now.
lets say right now its 02:31 I want an output of #[03:00,03:30,04:00,04:30...03:00(of the next day)]
if its 02:29 then I want #[02:30,03:00 and so on till the next day at 02:30].
right now I have the code below and it works almost all the time, yet rarely I get an output of all the NSDate objects that I want with a remainder of an extra minute(#[03:01,03:31:04:01...so on]).
any ideas ?
-(NSMutableArray*)TwentyFourHoursFromNowDivicedBy30Mins
{
NSMutableArray * dateArray = [NSMutableArray array];
NSCalendar * cal = [NSCalendar currentCalendar];
NSDateComponents * plusDays = [NSDateComponents new];
NSDate * now = [self changeTimeValue:[NSDate date]];
for( NSUInteger day = 0; day < 2; day++ )
{
[plusDays setDay:day];
[dateArray addObject:[cal dateByAddingComponents:plusDays toDate:now options:0]];
}
NSDate *startDate = [dateArray objectAtIndex:0];
NSDate *endDate = [dateArray objectAtIndex:1];
NSDateComponents *diff = [[NSDateComponents alloc] init];
[diff setMinute:0];
NSCalendar *calz = [NSCalendar currentCalendar];
NSDate *tmp = startDate;
NSMutableArray *dates = [NSMutableArray arrayWithObject:tmp];
while ([tmp laterDate:endDate] == endDate) {
[diff setMinute:[diff minute] + 30];
tmp = [calz dateByAddingComponents:diff toDate:startDate options:0];
[dates addObject:tmp];
}
return dates;
}
- (NSDate *)changeTimeValue:(NSDate *)dateValue{
NSDateComponents *time = [[NSCalendar currentCalendar]
components:NSHourCalendarUnit | NSMinuteCalendarUnit
fromDate:dateValue];
long val = 0;
NSDate *newDate = [[NSDate alloc] init];
NSInteger minutes = [time minute];
if(minutes > 0 && minutes < 30) {
val = 30 - minutes; NSTimeInterval aTimeInterval = [dateValue
timeIntervalSinceReferenceDate] + 60 * val + minutes;
newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
return newDate;
} else if(minutes > 30 && minutes < 60) {
val = 60 - minutes;
NSTimeInterval aTimeInterval = [dateValue timeIntervalSinceReferenceDate]
+ 60 * val;
newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
return newDate;
} else {
return newDate;
}
}
You're not zeroing out the seconds in your changeTimeValue, and in any case I think you've overcomplicated it. So I suspect you're subsequently seeing rounding issues. Just use NSDateComponents to do the whole job:
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [currentCalendar
components:NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit
fromDate:dateValue];
dateComponents.minute += 15;
dateComponents.minute -= dateComponents.minute%30;
return [currentCalendar dateFromComponents:dateComponents];
Related
I'm writing a GUI for a legacy data object where a date is saved in the integer properties day of the year and year (real "genius" design...)
How can I convert this data into day and month given the year?
I'm currently trying:
int theYear = 2016;
int theDayOfTheYear = 222;
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:theYear];
[components setDay:theDayOfTheYear];
NSDate* theDate = [gregorian dateFromComponents:components];
This seems a bit too hacky to me. It could be just coincidence that it works with days >31 - haven't found any mention of this in the NSDateComponents class reference.
When I debug, po theDate gives me 2016-08-08 22:00:00 +0000
--> close, but it should be 2016-08-09 (!)
To perform the reverse operation, i.e. to convert a normal DD-MM-YYYY date into day of the year, I'm using this code:
NSDate *fullDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSYearCalendarUnit
forDate:fullDate];
But I can't seem to find the proper methods to do the opposite...
Sometimes a test is all takes :)
Don't forget that NSDate are GMT, so you might want to add [[NSTimeZone localTimeZone] secondsFromGMT] seconds to it.
It seems that you have it working :)
- (void) testDate
{
int startYear = 2016;
int startMonth = 1;
int startDay = 1;
// Create the startDate
NSDateComponents * startDateComp = [NSDateComponents new];
startDateComp.day = startDay;
startDateComp.month = startMonth;
startDateComp.year = startYear;
NSDate * startDate = [[NSCalendar currentCalendar] dateFromComponents:startDateComp];
for(int i=0 ; i < 365; i++)
{
// add i day to startDate
NSDate * testDate = [startDate dateByAddingTimeInterval:i * 24 * 60 * 60];
NSUInteger dayOfYear = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSYearCalendarUnit
forDate:testDate];
XCTAssert(dayOfYear == (i + 1), #"the day of the year should be i + 1");
// Create a date using day of year
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:startYear];
[components setDay:dayOfYear];
NSDate* resultDate = [[NSCalendar currentCalendar] dateFromComponents:components];
// testing result date against test date
NSInteger test, result;
test = [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:testDate];
result = [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:resultDate];
XCTAssert(test == result);
test = [[NSCalendar currentCalendar] component:NSCalendarUnitMonth fromDate:testDate];
result = [[NSCalendar currentCalendar] component:NSCalendarUnitMonth fromDate:resultDate];
XCTAssert(test == result);
test = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:testDate];
result = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:resultDate];
XCTAssert(test == result);
}
Please try this. Its the larger calendar unit NSCalendarUnitEra :)
NSDate *fullDate = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];
gregorian.timeZone = [NSTimeZone systemTimeZone];
NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSCalendarUnitDay
inUnit:NSCalendarUnitEra
forDate:fullDate];
NSDateComponents *dateCom = [[NSDateComponents alloc] init];
dateCom.day = dayOfYear;
NSDate *expectedDate = [gregorian dateFromComponents:dateCom];
NSLog(#"%#",expectedDate);
I new in cocoa programing and I want to know how I get the number of working days between to dates. So only from Monday to Friday. Thanks.
NSDate *startDate = ...;
NSDate *stopDate = ...;
NSDateFormatter *df = [NSDateFormatter new];
df.dateFormat = #"yyyy-MM-dd";
startDate = [df dateFromString:[df stringFromDate:startDate]]; // get start of the day
NSDateComponents *comps = [NSDateComponents new];
comps.day = 1; // one day in NSDateComponents
NSUInteger count = 0;
while ([stopDate timeIntervalSinceDate:startDate] >= 0) {
NSInteger weekday = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:startDate].weekday;
if (weekday != 1 && weekday != 6) ++count; // filter out weekend days - 6 and 1
startDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:startDate options:0]; // increment start day
}
I need Objective C method for converting Gregorian date to Julian days same as this PHP method (GregorianToJD).
Precision: Incorporating time of day in Julian Date conversions
These Julian date conversion methods yield results identical to the U.S. Naval Observatory Online Julian Date Converter, which is more precise than NSDateFormatter's Julian Date conversion. Specifically, the functions below incorporate time-of-day (e.g. hour, minute and seconds), whereas NSDateFormatter rounds to noon GMT.
Swift examples:
func jdFromDate(date : NSDate) -> Double {
let JD_JAN_1_1970_0000GMT = 2440587.5
return JD_JAN_1_1970_0000GMT + date.timeIntervalSince1970 / 86400
}
func dateFromJd(jd : Double) -> NSDate {
let JD_JAN_1_1970_0000GMT = 2440587.5
return NSDate(timeIntervalSince1970: (jd - JD_JAN_1_1970_0000GMT) * 86400)
}
Objective-C examples:
double jdFromDate(NSDate *date) {
double JD_JAN_1_1970_0000GMT = 2440587.5;
return JD_JAN_1_1970_0000GMT + date.timeIntervalSince1970 / 86400;
}
NSDate dataFromJd(double jd) {
double JD_JAN_1_1970_0000GMT = 2440587.5;
return [[NSDate alloc] initWithTimeIntervalSince1970: (jd - JD_JAN_1_1970_0000GMT) * 86400)];
}
Note: Research confirms that the accepted answer rounds the date to a 24-hour interval because it uses the g format-specifier of NSDateFormatter, which returns the Modified Julian Day, according to the UNICODE standard's Date Format Patterns that Apple's date formatting APIs adhere to (according to the Date Formatting Guide).
According to http://en.wikipedia.org/wiki/Julian_day, the Julian day number for January 1, 2000, was 2,451,545. So you can compute the number of days between your date and this
reference date. For example (Jan 1, 2014):
NSUInteger julianDayFor01012000 = 2451545;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.year = 2014;
comp.month = 1;
comp.day = 1;
NSDate *date = [cal dateFromComponents:comp];
comp.year = 2000;
comp.month = 1;
comp.day = 1;
NSDate *ref = [cal dateFromComponents:comp];
NSDateComponents *diff = [cal components:NSDayCalendarUnit fromDate:ref toDate:date options:0];
NSInteger julianDays = diff.day + julianDayFor01012000;
NSLog(#"%ld", (long)julianDays);
// Output: 2456659
This gives the same result as http://www.php.net/manual/en/function.gregoriantojd.php:
<?php
$jd = GregorianToJD(1, 1, 2014);
echo "$jd\n";
?>
Inverse direction (Julian days to Gregorian year/month/day):
NSInteger julianDays = 2456659; // From above example
NSUInteger julianDayFor01012000 = 2451545;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.year = 2000;
comp.month = 1;
comp.day = 1;
NSDate *ref = [cal dateFromComponents:comp];
NSDateComponents *diff = [[NSDateComponents alloc] init];
diff.day = julianDays - julianDayFor01012000;
NSDate *date = [cal dateByAddingComponents:diff toDate:ref options:0];
comp = [cal components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:date];
NSLog(#"%04ld-%02ld-%02ld", (long)comp.year, (long)comp.month, (long)comp.day);
// Output: 2014-01-01
UPDATE: As Hot Licks correctly stated in a comment, it is easier to use a date
formatter with the "g" format:
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.year = 2014;
comp.month = 1;
comp.day = 1;
NSDate *date = [cal dateFromComponents:comp];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:#"g"];
NSInteger julianDays = [[fmt stringFromDate:date] integerValue];
NSLog(#"%ld", (long)julianDays);
// Output: 2456659
And for the inverse direction:
NSInteger julianDays = 2456659;
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:#"g"];
NSDate *date = [fmt dateFromString:[#(julianDays) stringValue]];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [cal components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:date];
NSLog(#"%04ld-%02ld-%02ld", (long)comp.year, (long)comp.month, (long)comp.day);
// Output: 2014-01-01
let date = Date() // now
let cal = Calendar.current
var day = 0
day = cal.ordinality(of: .day, in: .year, for: date) ?? 0
How to compare time in Objective C?
if (nowTime > 9:00 PM) && (nowTime < 7:00 AM)
{
doSomething;
}
If you want to get the current hour and compare it to some times, you're going to have to use NSDate, NSDateComponents, and NSCalendar.
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinute = [components minute];
NSInteger currentSecond = [components second];
if (currentHour < 7 || (currentHour > 21 || currentHour == 21 && (currentMinute > 0 || currentSecond > 0))) {
// Do Something
}
That will check if the time is between 9:00 PM and 7:00 AM. Of course, if you're going to want different times you'll have to change the code a little.
Read about NSDate, NSDateComponents, and NSCalendar to learn more.
Theres a perfect formula for this. Just for future references
Below is the sample code :
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
NSString *startTime = #"21:00";
NSString *endTime = #"07:00";
int stHr = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
int stMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
int enHr = [[[endTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
int enMin = [[[endTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
int formStTime = (stHr*60)+stMin;
int formEnTime = (enHr*60)+enMin;
int nowTime = (int)((currHr*60)+currtMin);
if(nowTime >= formStTime && nowTime <= formEnTime) {
// Do Some Nasty Stuff..
}
NSDate *now = [NSDate date];
if (([now compare:earlierDateVariable] == NSOrderedDescending) && ([now compare:laterDateVariable] == NSOrderedAscending ))
{
// Do something here...
}
To set earlierDate and laterDate, straight from Apple's documentation available here
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:22];
[comps setMonth:03];
[comps setYear:2011];
[comps setHour:21];
[comps setMinute:00];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *earlierDateVariable = [gregorian dateFromComponents:comps];
[comps release];
[gregorian release];
And the same goes for later date...
For checking current time or any time between two times ::
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
return [self isDateComponent:components withinStartHour:startH startMin:startM endHour:endH endMin:endM];
-(BOOL)isDateComponent:(NSDateComponents*)components withinStartHour:(int)startH startMin:(int)startM endHour:(int)endH endMin:(int)endM
{
if (endH < startH) {
return ( [self isDateComponent:components betweenStartHour:startH startmin:startM endHour:23 endMin:59] ||
[self isDateComponent:components betweenStartHour:0 startmin:0 endHour:endH endMin:endM] );
}
else {
return [self isDateComponent:components betweenStartHour:startH startmin:startM endHour:endH endMin:endM];
}
}
-(BOOL)isDateComponent:(NSDateComponents*)components betweenStartHour:(int)startH startmin:(int)startM endHour:(int)endH endMin:(int)endM
{
int currentH = components.hour;
int currentM = components.minute ;
DDLogVerbose(#"start : %i-%i, end : %i-%i, current:%i-%i",startH,startM,endH,endM,currentH,currentM);
startM = startM + startH * 60;
endM = endM + endH * 60;
currentM = components.minute + currentH*60;
if ( startM <= currentM && currentM < endM ) {
return YES;
}
else {
return NO;
}
}
I used the Answer Given above by rye. I just had to convert my 7:00 AM and 9:00 PM to 24 hours. Here's the method I used
/**
Willl return YES if the Restaurant is OPEN at the Moment else NO
*/
-(BOOL) isShopOpen:(NSString *) startTime closeTime:(NSString *) endTime{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
int stHr ;
int stMin ;
int enHr ;
int enMin ;
if([startTime containsString:#"PM"]){
startTime = [startTime stringByReplacingOccurrencesOfString:#" PM" withString:#""];
stHr=[[[startTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
stHr=stHr+12;
stMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
}else{
startTime = [startTime stringByReplacingOccurrencesOfString:#" AM" withString:#""];
stHr=[[[startTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
stMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
}
if([endTime containsString:#"PM"]){
endTime = [endTime stringByReplacingOccurrencesOfString:#" PM" withString:#""];
enHr=[[[endTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
enHr=enHr+12;
enMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
}else{
endTime = [endTime stringByReplacingOccurrencesOfString:#" AM" withString:#""];
enHr=[[[endTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
enMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
}
int formStTime = (stHr*60)+stMin;
int formEnTime = (enHr*60)+enMin;
int nowTime = (currHr*60)+currtMin;
if(nowTime >= formStTime && nowTime <= formEnTime) {
// Do Some Nasty Stuff..
return YES;
}else{
return NO;
}
}
If anybody needs, this is a code to create sections in a tableView according to the date of objects.
Method to get dates for today, yesterday, etc. (taken from ReMail project DateUtil class):
#define DATE_UTIL_SECS_PER_DAY 86400
-(void)refreshData {
//TODO(gabor): Call this every hour or so to refresh what today, yesterday, etc. mean
NSCalendar *gregorian = [NSCalendar currentCalendar];
self.today = [NSDate date];
self.yesterday = [today dateByAddingTimeInterval:-DATE_UTIL_SECS_PER_DAY];
self.lastWeek = [today dateByAddingTimeInterval:-6*DATE_UTIL_SECS_PER_DAY];
self.todayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:today];
self.yesterdayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:yesterday];
self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
}
Method to sort tableData for table view sections according to date:
// Sort tableData objects according to the date
for (MCMessage *mcMessage in self.tableData) {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:mcMessage.dateTime];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSLog(#"Day:%d, Month:%d, Year:%d. Today day:%d. Yesterday:%d", day, month, year, dateUtil.todayComponents.day, dateUtil.yesterdayComponents.day);
if ((dateUtil.todayComponents.day == day) && (dateUtil.todayComponents.month == month) && (dateUtil.todayComponents.year == year))
{
[self.todayData addObject:mcMessage];
}
else if ((dateUtil.yesterdayComponents.day == day) && (dateUtil.yesterdayComponents.month == month) && (dateUtil.yesterdayComponents.year == year))
{
[self.yesterdayData addObject:mcMessage];
}
else
{
[self.soonerData addObject:mcMessage];
}
}
how can I compare two dates return number of days.
Ex: Missing X days of the Cup.
look my code.
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"d MMMM,yyyy"];
NSDate *date1 = [df dateFromString:#"11-05-2010"];
NSDate *date2 = [df dateFromString:#"11-06-2010"];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
//int days = (int)interval / 30;
//int months = (interval - (months/30)) / 30;
NSString *timeDiff = [NSString stringWithFormat:#"%dMissing%d days of the Cup",date1,date2, fabs(interval)];
label.text = timeDiff; // output (Missing X days of the Cup)
From Apple's example, basically use an NSCalendar:
NSDate * date1 = <however you initialize this>;
NSDate * date2 = <...>;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:date1
toDate:date2 options:0];
NSInteger months = [components month];
NSInteger days = [components day];
You can use next category:
#interface NSDate (Additions)
-(NSInteger)numberOfDaysUntilDay:(NSDate *)aDate;
-(NSInteger)numberOfHoursUntilDay:(NSDate *)aDate;
#end
#implementation NSDate (Additions)
const NSInteger secondPerMunite = 60;
const NSInteger munitePerHour = 60;
const NSInteger hourPerDay = 24;
-(NSInteger)numberOfDaysUntilDay:(NSDate *)aDate
{
NSInteger selfTimeInterval = [aDate timeIntervalSinceDate:self];
return abs(selfTimeInterval / (secondPerMunite * munitePerHour * hourPerDay));
}
-(NSInteger)numberOfHoursUntilDay:(NSDate *)aDate
{
NSInteger selfTimeInterval = [aDate timeIntervalSinceDate:self];
return abs(selfTimeInterval / (secondPerMunite * munitePerHour));
}
#end
Need to call this method and set 2 dates only which we want to calculate differently.
-(void) calculateSleepHours:(NSDate *)sleepDate :(NSDate *)wakeStr
{
if (sleepDate !=nil && wakeStr!=nil) {`enter code here`
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ssZ"];
NSDate *date1 = [ApplicationManager getInstance].sleepTime;;
NSDate *date2 = [ApplicationManager getInstance].wakeupTime;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:date1
toDate:date2 options:0];
NSInteger months = [components month];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger minute=[components minute];
NSInteger second=[components second];
DLog(#"Month %ld day %ld hour is %ld min %ld sec %ld ",(long)months,(long)days,(long)hours,(long)minute,(long)second);
sleepHours.text=[NSString stringWithFormat:#"Hour %ld Min %ld Sec %ld",(long)hours,(long)minute,(long)second];
}
}
Try this category:
#interface NSDate (DateUtils)
-(NSInteger)numberOfDaysUntilDay:(NSDate *)aDate;
#end
#implementation NSDate (DateUtils)
-(NSInteger)numberOfDaysUntilDay:(NSDate *)aDate
{
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitDay
fromDate:self
toDate:aDate options:kNilOptions];
return [components day];
}
#end
You can use this category by adding an import:
#import "NSDate+DateUtils.h"
And call it from your code:
NSInteger days = [myDate numberOfDaysUntilDay:someOtherDate];