NSDate / NSCalender count days in year - xcode

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]);
}
}

Related

How to calculate and display 4 other days from the day i add in date picker and set local notification to it?

In my App, When i select a day in the datepicker it should automatically calculate and display 4 other days and also it should notify on the corresponding days. For Eg. if i enter 19-08-2014, it should calculate and display the 3rd day, the 7th day, the 14th day and the 21st day from 19-08-2014(the day i entered in datepicker).
How would i achieve this. Any help would be greatly appreciated.
I have added my current code for your reference. This doesnt serve my purpose.
Kindly Help.
(IBAction)save:(UIButton *)sender {
NSDate *pickerDate = [self.picker date];
UILocalNotification *localNotif = [[UILocalNotification alloc]init];
//localNotif.alertBody = _enterText.text;
localNotif.alertBody = #"Please Take Your Rabipur Dosage";
localNotif.fireDate = pickerDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.soundName = (UILocalNotificationDefaultSoundName);
localNotif.applicationIconBadgeNumber = 1;
//localNotif.repeatInterval = NSDayCalendarUnit;
[[UIApplication sharedApplication]scheduleLocalNotification:localNotif];
[self dismissViewControllerAnimated:YES completion:nil];
}
Create an NSDateComponents object with the date difference you want to add, and add it to pickerDate via NSCalendar -dateByAddingComponents:toDate:options. Then create your notification based on the resulting date.
In this case, something like this:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:3];
NSDate *reminderDate = [gregorian dateByAddingComponents:offsetComponents toDate:pickerDate options:0];
Repeat for 7th, 14th, and 21st day.

Calculate seconds between current time and next event

This should be simple, but it's proving challenging for me. I'd like to know the best approach to calculating the difference in seconds between [NSDate date] and a future event x seconds from that time. There are several different types of event, and each event may occur several times a day, and at different times, depending what day of the week it happens to be.
What I am trying to do is have the user select an event type from a picker and then set an alarm in Notification Center for the next occurrence of that event based on their selection. I have everything working fine, except for the seconds calculation.
So, for example, let's say it's 9am on a Monday. I'd like to determine how many seconds it would be between now and a user selected event that regularly occurs every Tuesday, Thursday, and Saturday at 10am, 4pm, and 11pm on each day, or on Sunday at 1pm. How would you approach this most efficiently?
When you're talking about a time or date like "next Thursday at 1 PM", that's information that only makes sense in the context of a calendar. NSDate is not going to provide you with much help. It would perhaps be more appropriately named NSPointInTime. It's just a number of seconds that have passed from some earlier, arbitrary reference point in time. It has no notion of weekdays, ante/post meridiem, or even hour of the day.
The two objects that do know about those sorts of thing are NSDateComponents and NSCalendar. Working together, they can create an NSDate from a specification like "next Thursday at 1PM".
You can decompose any date into components using -[NSCalendar components:fromDate:], and you can then use other NSDateComponents objects to perform arithmetic on the individual pieces of information. Find the weekday of today, for example, and its difference from Thursday. Then use -[NSCalendar dateByAddingComponents:toDate:options:] to create a new date based on that offset.
#interface NSCalendar (NextWeekday)
- (NSInteger)maxWeekday;
- (NSDate *)dateFromComponents:(NSDateComponents *)comps
forNextWeekday:(NSInteger)weekday
atHour:(NSInteger)hour;
#end
#implementation NSCalendar (NextWeekday)
- (NSInteger)maxWeekday
{
return [self maximumRangeOfUnit:NSWeekdayCalendarUnit].length;
}
- (NSDate *)dateFromComponents:(NSDateComponents *)comps
forNextWeekday:(NSInteger)weekday
atHour:(NSInteger)hour
{
NSInteger diff = weekday - [comps weekday];
if( diff < 0 ){
diff += [self maxWeekday];
}
NSDateComponents * weekdayOffset = [NSDateComponents new];
[weekdayOffset setWeekday:diff];
[comps setHour:hour];
return [self dateByAddingComponents:weekdayOffset
toDate:[self dateFromComponents:comps]
options:0];
}
#end
#define GREGORIAN_THURSDAY 5
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSCalendar * cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents * wednesday = [NSDateComponents new];
[wednesday setDay:3];
[wednesday setWeekday:4];
[wednesday setMonth:6];
[wednesday setYear:2013];
NSDateComponents * friday = [NSDateComponents new];
[friday setDay:5];
[friday setWeekday:6];
[friday setMonth:6];
[friday setYear:2013];
NSDateComponents * now = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit
fromDate:[NSDate date]];
NSDateComponents * lastSatOfDecember = [NSDateComponents new];
[lastSatOfDecember setDay:29];
[lastSatOfDecember setWeekday:7];
[lastSatOfDecember setMonth:12];
[lastSatOfDecember setYear:2012];
NSLog(#"From Wednesday: %#", [cal dateFromComponents:wednesday
forNextWeekday:GREGORIAN_THURSDAY
atHour:13]);
NSLog(#"From Friday: %#", [cal dateFromComponents:friday
forNextWeekday:GREGORIAN_THURSDAY
atHour:13]);
NSLog(#"From now: %#", [cal dateFromComponents:now
forNextWeekday:GREGORIAN_THURSDAY
atHour:13]);
NSLog(#"Crossing over the year: %#", [cal dateFromComponents:lastSatOfDecember
forNextWeekday:GREGORIAN_THURSDAY
atHour:13]);
}
return 0;
}

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;

How can I get an NSDate for the first day of the next week of the month

Given an arbitrary date, I need to find the date of the first day of the next week of the month. Note that it is not as simple as adding 7 days to the current date because the last week of the month may be less than 7 days. Here is the code I'm using now:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSWeekOfMonthCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit fromDate:currentDate];
NSLog(#"week of month: %ld", [components weekOfMonth]);
[components setWeekOfMonth:[components weekOfMonth] + 1];
NSLog(#"new week of month: %ld", [components weekOfMonth]); //week of month is now 2
[components setWeekday:1];
NSDate *nextWeek = [calendar dateFromComponents:components];
As an example, currentDate is set to 2012-10-01. In this example nextWeek is always 2012-10-01. It appears that sending setWeekOfMonth: does not increment the other date components in the NSDateComponents object. Do I have the wrong date components configured, or is setWeekOfMonth: not supposed to work like that?
So.... Let's start with an NSDate and an NSCalendar:
NSDate *date = ...;
NSCalendar *cal = [NSCalendar currentCalendar];
Figure out what day of the week that date is:
NSInteger weekdayOfDate = [cal ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:date];
NSInteger numberOfDaysToStartOfCurrentWeek = weekdayOfDate - 1;
Let's move that date into the next week:
NSDateComponents *oneWeek = [[NSDateComponents alloc] init];
[oneWeek setWeek:1]; // add one week
[oneWeek setDay:-numberOfDaysToStartOfCurrentWeek]; // ... and subtract a couple of days to get the first day of the week
NSDate *startOfNextWeek = [cal dateByAddingComponents:oneWeek toDate:date options:0];
At this point, you have a date that points to the first day of the next week. Now we should verify that it's still in the same month:
NSDateComponents *monthOfNextWeek = [cal components:NSMonthCalendarUnit fromDate:startOfNextWeek];
NSDateComponents *monthOfThisWeek = [cal components:NSMonthCalendarUnit fromDate:date];
if ([monthOfNextWeek month] != [monthOfThisWeek month]) {
// the first day of the next week is not in the same month as the start date
}
When I run this, I get that the start of next week is 30 Dec 2012 (a Sunday, because my calendar's weeks start on Sunday).
If, however, I want the first day of the week to start on Monday, I can preface this code with:
[cal setFirstWeekday:2]; // the first day of the week is the second day (ie, Monday, because Sunday = 1)
If I do this, then the startOfNextWeek results in 31 Dec 2012.
Will this be a valid answer :
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:#"en_US_POSIX"]];
[dateFormatter setDateFormat:#"EEE"];
NSDate *date=[NSDate date];
NSString *dateString=[dateFormatter stringFromDate:date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [NSDateComponents new];
[calendar setFirstWeekday:1];//1 for Mon
NSDate *newDate=date;
while (![dateString isEqualToString:#"Mon"]) {
components.day = 1;
newDate = [calendar dateByAddingComponents:components toDate:newDate options:0];
dateString=[dateFormatter stringFromDate:newDate];
}
NSLog(#"Upcoming week Date=%#",newDate);

NSDate hours are not correct after constructing date from components

I'm trying to construct a date from two different dates. When I break down both dates into their respective components and re-assemble them into the new date.. everything seems to be correct except the hours. Im sure its something simple that has to do with the timezone or the NSGregorianCalendar, but I am new to iOS, and programming NSCalendar. Im hoping someone will catch the simple mistake Im making.
//grab today's date so we can brek it down into components
NSDate *todayDate = [NSDate date];
NSLog(#"Todays Date: %#", todayDate);
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
//break down the stored date into components
NSDateComponents *theTime = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:storedIncorrectDate];
NSLog(#"Incorrect Calendar Components %#", theTime);
NSDateComponents *todayCalendarComponents = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:todayDate];
NSInteger currentYear = [todayCalendarComponents year];
NSLog(#"The Year: %i", currentYear);
NSInteger currentMonth = [todayCalendarComponents month];
NSLog(#"The Month: %i", currentMonth);
NSInteger currentDay = [todayCalendarComponents day];
NSLog(#"The Day: %i", currentDay);
NSLog(#"Today's Calendar Components %#", todayCalendarComponents);
NSInteger theHours = [theTime hour];
NSLog(#"Hours: %i", theHours);
NSInteger theMinutes = [theTime minute];
NSLog(#"Minutes: %i", theMinutes);
NSInteger theSeconds = [theTime second];
NSLog(#"Seconds: %i", theSeconds);
//build my new date and store it before we play the affirmation.
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:theHours];
[components setMinute:theMinutes];
[components setSecond:theSeconds];
[components setYear:currentYear];
[components setMonth:currentMonth];
[components setDay:currentDay];
[components setTimeZone:[NSTimeZone localTimeZone]];
NSLog(#"The Components: %#", components);
NSCalendar *updatedCal = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *revisedCorrectedDate = [updatedCal dateFromComponents:components];
NSLog(#"The Hours: %i", theHours);
NSLog(#"The New and Corrected Date: %#", revisedCorrectedDate);
The result of the log printing the revisedCorrectedDate shows everything correct that I set except the hours. This has to be a simple fix.. I just don't see it. Thank you in advance!
Are you sure it's incorrect? When I run this code, I get:
2012-06-03 18:13:36.130 Untitled[39805:707] The New and Corrected
Date: 2012-06-04 01:13:36 +0000
It's currently 6/3/12 18:13:36 here, and the date displayed is 6/4/12 01:13:36, which is the correct time, in UTC (notice the +0000 at the end).

Resources