Xcode time difference in minutes fails - xcode

quick question I used the following code to retrieve a difference between two timestamps.
The minutes are given to me now in 0.5 hrs.
how do I get that into minutes (NSInteger format)?
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease]];
[dateFormatter setDateFormat:#"mm:ss"];
NSDate* firstDate = [dateFormatter dateFromString:#"06:00"];
NSDate* secondDate = [dateFormatter dateFromString:#"17:30"];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
I'm using an NSInteger to get the full hours, but can't figure out the minutes... must be too late at night for me :-/
NSInteger hoursBetweenDates = timeDifference / 60;
NSInteger minutesBetweenDates = ??;
NSLog(#"RAW: %f", timeDifference);
NSLog(#"Hours: %i", hoursBetweenDates);
NSLog(#"Minutes: %i", minutesBetweenDates);
Thanks guys! :-D

The NSTimeInterval is in seconds. So minutes would be diff/60.0 and hours would be diff/3600.0.

you could do:
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
int minute = (int)timeDifference % 3600 / 60;

Related

Get first day in a month from NSCalendar

I have this subset of a method that needs to get day one of the current month.
NSDate *today = [NSDate date]; // returns correctly 28 february 2013
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *dayOneInCurrentMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
dayOneInCurrentMonth then prints out 2013-03-01 09:53:49 +0000, the first day of the next month.
How do I get day one of the current month?
Your logic is wrong: Instead of setting the date's day to 1, you're adding a day to the current date.
Try something like that:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;
NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
You want [NSCalender dateFromComponents:] instead:
NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
Easy way of getting to the 1st from a given date:
NSDate *first = [gregorian dateBySettingUnit:NSCalendarUnitDay value:1 ofDate:date options:0];
Easy Way to get first and last date of previous month is :
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comp = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:[NSDate date]];
//TO GET PREVIOUS MONTH LAST DAY
[comp setMonth:[comp month]];
[comp setDay:1];
NSDate *tDateMonth = [gregorian dateFromComponents:comp];
NSLog(#"LAST DAY OF PREVIOUS MONTH ; %#", tDateMonth);
//TO GET PREVIOUS MONTH FIRST DAY
[comp setMonth:[comp month]-1];
[comp setDay:3];
NSDate *td = [gregorian dateFromComponents:comp];
NSLog(#"FIRST DAY OF PREVIOUS MONTH ; %#", td);
Hope this helps
By creating new variable is expensive on memory usage, it's better using date formatter to get the first day of the current month
today = [NSDate date];
firstDayDateFormatter = [[NSDateFormatter alloc] init];
[firstDayDateFormatter setDateFormat:#"01-MM-yyyy"];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US"]];
firstDayOfTheMonth = [mdfDateFormat dateFromString:[firstDayDateFormatter stringFromDate:today]];
NSDate *startDate = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:NULL forDate:date];
return startDate;

NSDate / NSCalender count days in year

I am making an app that calculates salaries based on the years somebody is working for a firm. The user enter 2 dates, the first one is the day he started working (let's say 1/12/2010) and the second is the end date (let's say 1/02/2012). So far i know the total days he worked but i want to be more specific in order to calculate that he worked:
30 days in 2010 * 30$ per day = 90$
365 days in 2011 * 35$ per day = 12775$
32 days in 2012 * 40$ per day = 1280$
It's the first time i am working with dates and calendars and as you can guess i am totally unfamiliar with them.
Try this code :
-(NSInteger)daysBetweenTwoDates:(NSDate *)fromDateTime andDate:(NSDate*)toDateTime{
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:toDateTime];
NSDateComponents *difference = [calendar components:NSDayCalendarUnit fromDate:fromDate toDate:toDate options:0];
return [difference day]+1;//+1 as if start and end both date are same, so 1 day worked.
}
- (IBAction)calculate:(id)sender {
NSDate *startDate=[self.startDate dateValue];//taking from datepicker
NSDate *endDate=[self.endDate dateValue];//taking from datepicker
NSTimeZone *gmt=[NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSDateFormatter *dateFormatterYYYY=[NSDateFormatter new];
[dateFormatterYYYY setTimeZone:gmt];
[dateFormatterYYYY setDateFormat:#"YYYY"];
NSDateFormatter *dateFormatterDDMMYYYY=[NSDateFormatter new];
[dateFormatterDDMMYYYY setDateFormat:#"dd/mm/YYYY"];
[dateFormatterDDMMYYYY setTimeZone:gmt];
//1. startDate to 31/12/StartDateYear
//2. loop to endDateYear
//3. 01/01/endDateYear to endDate
/* step 1 */
//find 31/12/StartDateYear
NSLog(#"YYYY ; %#",[dateFormatterYYYY stringFromDate:startDate]);
NSString *lastDateOfStartYearString=[NSString stringWithFormat:#"31/12/%#",[dateFormatterYYYY stringFromDate:startDate]];
NSDateFormatter *dateFormatddMMyyyy=[NSDateFormatter new];
[dateFormatddMMyyyy setDateFormat:#"dd'/'MM'/'yyyy"];
NSDate *lastDateOfStartYear=[dateFormatddMMyyyy dateFromString:lastDateOfStartYearString];
//no. of days
NSInteger year=[[dateFormatterYYYY stringFromDate:startDate]integerValue];
NSInteger days=[self daysBetweenTwoDates:startDate andDate:lastDateOfStartYear];
//add in dictionary
NSMutableDictionary *daysForYearDictionary=[NSMutableDictionary new];
[daysForYearDictionary setValue:#(days) forKey:[NSString stringWithFormat:#"%ld",year]];
/* step 2*/
NSInteger nextYearAfterStart=[[dateFormatterYYYY stringFromDate:startDate]integerValue]+1;
NSInteger previousYearBeforeEnd=[[dateFormatterYYYY stringFromDate:endDate]integerValue]-1;
for (NSInteger yearCounter=nextYearAfterStart; yearCounter<=previousYearBeforeEnd; yearCounter++) {
NSString *firstDateString=[NSString stringWithFormat:#"1/1/%ld",yearCounter];
NSDate *firstDate=[dateFormatddMMyyyy dateFromString:firstDateString];
NSString *lastDateString=[NSString stringWithFormat:#"31/12/%ld",yearCounter];
NSDate *lastDate=[dateFormatddMMyyyy dateFromString:lastDateString];
//no. of days
days=[self daysBetweenTwoDates:firstDate andDate:lastDate];
//add in dictionary
[daysForYearDictionary setValue:#(days) forKey:[NSString stringWithFormat:#"%ld",yearCounter]];
}
/* step 3 */
//find 1/1/EndDateYear
NSString *firstDateOfStartYearString=[NSString stringWithFormat:#"1/1/%#",[dateFormatterYYYY stringFromDate:endDate]];
NSDate *firstDateOfEndYear=[dateFormatddMMyyyy dateFromString:firstDateOfStartYearString];
//no. of days
year=[[dateFormatterYYYY stringFromDate:endDate]integerValue];
days=[self daysBetweenTwoDates:firstDateOfEndYear andDate:endDate];
//add in dictionary
[daysForYearDictionary setValue:#(days) forKey:[NSString stringWithFormat:#"%ld",year]];
//printing
for (NSString *yearStr in daysForYearDictionary) {
NSLog(#"Year : %#, Days Worked : %#",yearStr,[daysForYearDictionary valueForKey:yearStr]);
}
}

Interval between 2 NSDates

I am trying to calculate an interval between now and a user defined date in days so that the results appear in a label on tapping a button.
The difference is always -4080 I am not sure what is wrong with my equation.
Thank you for your help
- (void)LabelChange2:(id)sender{
NSDateFormatter *df3 = [[NSDateFormatter alloc] init];
df3.dateStyle = NSDateFormatterMediumStyle;
labelDOB.text = [NSString stringWithFormat:#"%#",
[df3 stringFromDate:datepick.date]];
}
NSDate * df3 = [datePick date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components: NSDayCalendarUnit
fromDate: [NSDate date]
toDate: df3
options: 0];
int days = [comps day];
labelResult.text = [NSString stringWithFormat:#"%i", days];
Your code works fine. However if I run the code with the datePick pointer set to nil I will get an answer of -4080 from this code. You should check your connections to the UIDatePicker.

NSDate: Right way to work with time of day?

I am working with a schedule that specifies times of day, such as 10:30 AM. I do not know the dates, however. I'm going to store these as values in a NSDictionary and would like to deal with them in a straightforward way.
I can't use NSDate, since I don't have a date. At least, not in a straightforward way.
The other way that seems obvious is NSTimeInterval, but that looks like it's probably a source of very subtle errors. I'm thinking in particular of daylight savings time (which is on my mind this week for some reason!).
Other than that, the only things that really spring to mind are keeping it in a formatted string or encoding it in a NSNumber (like hours * 60 + minutes). Both of which would work out fine, of course, but seem like I'm inventing a square wheel where I'm sure there's already a round one somewhere.
What's the least against the grain way of dealing with raw times using Cocoa?
The short answer is that there's no built-in mechanism for storing time-of-day, so just use whatever is most convenient to you. I've used strings in the past using my own encoding and parsing code, (e.g., "22:00") because they're easy to read and debug, but there's nothing wrong with storing seconds or minutes past midnight as you suggest. Just remember that you'll have to do the math yourself.
How ever you do it, you will need separate year, month, day, hour, minute, and second values so that you can construct an NSDate from NSDateComponents, using NSCalendar's -dateFromComponents: method.
And as others have said, you cannot set the time-of-day by adding hours and minutes to an existing NSDate because if you cross a DST boundary you won't get the value you expect. (However, I assume you can still add day and month components without worrying about DST)
So, I guess there's no simple inbuilt way of doing this. It also looks like the only way to get Cocoa to build the time I expect on DST boundaries is with strings.
So for posterity, it looks like I'll be using something like this.
Test harness:
//
// TimeTest.m
//
#import <Foundation/Foundation.h>
#import "Utility.h"
id utility;
void testTime( NSTimeInterval time ) {
id gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar] autorelease];
id oneDay = [[[NSDateComponents alloc] init] autorelease];
[oneDay setDay: 1];
id thisDay = [gregorian dateFromComponents: [gregorian components: (NSEraCalendarUnit | NSYearCalendarUnit)
fromDate: [NSDate date]]];
for (NSInteger dayIdx = 0; dayIdx < 365; ++dayIdx ) {
NSDate *dateTime = [utility timeInSeconds: time
onDate: thisDay];
NSLog( #"%#", dateTime );
thisDay = [gregorian dateByAddingComponents: oneDay
toDate: thisDay
options: 0];
}
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
utility = [[[Utility alloc] init] autorelease];
testTime( ((10 * 60.0) + 0.0) * 60.0 );
testTime( ((9 * 60.0) + 30.0) * 60.0 );
[pool drain];
return 0;
}
Utility header:
//
// Utility.h
//
#import <Foundation/Foundation.h>
#interface Utility : NSObject {
NSCalendar *gregorian;
NSDateFormatter *dateWithoutTimeFormatter, *dateWithTimeFormatter;
}
- (NSDate *)timeInHours: (NSInteger)hours
minutes: (NSInteger)minutes
seconds: (NSInteger)seconds
onDate: (NSDate *)inDate;
- (NSDate *)timeInSeconds: (NSTimeInterval)inTime
onDate: (NSDate *)inDate;
#end
Utility implementation:
//
// Utility.m
//
#import "Utility.h"
#interface Utility()
#property (nonatomic, readwrite, retain) NSCalendar *gregorian;
#property (nonatomic, readwrite, retain) NSDateFormatter *dateWithoutTimeFormatter, *dateWithTimeFormatter;
#end
#implementation Utility
#synthesize gregorian, dateWithoutTimeFormatter, dateWithTimeFormatter;
- (NSDate *)timeInHours: (NSInteger)hours
minutes: (NSInteger)minutes
seconds: (NSInteger)seconds
onDate: (NSDate *)inDate;
{
id timeStr = [[NSMutableString alloc] initWithFormat: #"%02d:%02d:%02d", hours, minutes, seconds];
id dateStr = [dateWithoutTimeFormatter stringFromDate: inDate];
id dateTimeStr = [[NSString alloc] initWithFormat: #"%# %#", dateStr, timeStr];
[timeStr release];
id dateTime = [dateWithTimeFormatter dateFromString: dateTimeStr];
[dateTimeStr release];
return dateTime;
}
- (NSDate *)timeInSeconds: (NSTimeInterval)inTime
onDate: (NSDate *)inDate;
{
NSAssert1( inTime < 24.0 * 3600.0, #"Time %f must be less than 24hrs", inTime );
double temp = inTime;
int hours = rintf(floor( temp / 3600.0 ));
temp -= ( hours * 3600 );
int minutes = rintf(floorf( temp / 60.0 ));
temp -= ( minutes * 60 );
int seconds = rintf( temp );
return [self timeInHours: hours
minutes: minutes
seconds: seconds
onDate: inDate];
}
- (id)init;
{
if (( self = [super init] )) {
self.gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar] autorelease];
self.dateWithoutTimeFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateWithoutTimeFormatter setDateFormat: #"yyyy-MM-dd"];
self.dateWithTimeFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateWithTimeFormatter setDateFormat: #"yyyy-MM-dd HH:mm:ss"];
}
return self;
}
- (void)dealloc;
{
self.gregorian = nil;
self.dateWithoutTimeFormatter = nil;
self.dateWithTimeFormatter = nil;
[super dealloc];
}
#end
Why bother with a separate unit for this? Well, I've written enough date formatting code to know that constructing NSCalendar and NSDateFormatter on the fly utterly kills performance.
You can use NSDateComponents to store only the components you need (hour and minutes for example), and then use NSCalendar dateByAddingComponents:toDate:options: to create an absolute date reference, when you need using the serialized components and a base date.

Is there a better way to find midnight tomorrow?

Is there a better way to do this?
-(NSDate *)getMidnightTommorow {
NSCalendarDate *now = [NSCalendarDate date];
NSCalendarDate *tomorrow = [now dateByAddingYears:0 months:0 days:1 hours:0 minutes:0 seconds:0];
return [NSCalendarDate dateWithYear:[tomorrow yearOfCommonEra]
month:[tomorrow monthOfYear]
day:[tomorrow dayOfMonth]
hour:0
minute:0
second:0
timeZone:[tomorrow timeZone]];
}
Note that I always want the next midnight, even if it happens to be midnight when I make that call, however if it happens to be 23:59:59, I of course want the midnight that is coming in one second.
The natural language functions seem flaky, and I'm not sure what Cocoa would do if I pass 32 in the "day" field. (If that'd work I could drop the [now dateByAddingYears:...] call)
From the documentation:
Use of NSCalendarDate strongly
discouraged. It is not deprecated yet,
however it may be in the next major OS
release after Mac OS X v10.5. For
calendrical calculations, you should
use suitable combinations of
NSCalendar, NSDate, and
NSDateComponents, as described in
Calendars in Dates and Times
Programming Topics for Cocoa.
Following that advice:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
components = [gregorian components:unitFlags fromDate:tomorrow];
components.hour = 0;
components.minute = 0;
NSDate *tomorrowMidnight = [gregorian dateFromComponents:components];
[gregorian release];
[components release];
(I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.)
Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although dateFromComponents: may tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it.
Nope - it'll be the same way you use to find midnight today.
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:(24 * 60 * 60)];
NSDateComponents *components = [gregorian components:(NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit)
fromDate:tomorrow];
NSDate *midnight = [gregorian dateFromComponents:components];
[NSDate dateWithNaturalLanguageString:#"midnight tomorrow"];
Convert your current date and time to a Unix date (seconds since 1970) or DOS style (since 1980), then add 24 hours and convert it back. Then reset the hours, minutes and seconds to zero to get to midnight.
You could try this way:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
NSDate *tomorrow = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0]; //it gives us tomorrow with current time
NSDate *midnight = [calendar startOfDayForDate:tomorrow]; //here we get next midnight
It is also easy to retrieve the seconds interval if needed to set up an NSTimer:
double intervalToMidnight = midnight.timeIntervalSinceNow;

Resources