How to get next week start and end date in Objective-c? - objective-c

I have try to get next week start and end date but I have got current week start and end date.How can get next week start and end date in Objective-c.

You can get all dates of this week and next week using following code:-
NSArray * allDatesOfThisWeek = [self daysThisWeek];
NSArray * allDatesOfNextWeek = [self daysNextWeek];
Following methods are used for calculating dates of this week:-
-(NSArray*)daysThisWeek
{
return [self daysInWeek:0 fromDate:[NSDate date]];
}
-(NSArray*)daysNextWeek
{
return [self daysInWeek:1 fromDate:[NSDate date]];
}
-(NSArray*)daysInWeek:(int)weekOffset fromDate:(NSDate*)date
{
NSCalendar *calendar = [NSCalendar currentCalendar];
//ask for current week
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps=[calendar components:NSWeekCalendarUnit|NSYearCalendarUnit fromDate:date];
//create date on week start
NSDate* weekstart=[calendar dateFromComponents:comps];
NSDateComponents* moveWeeks=[[NSDateComponents alloc] init];
moveWeeks.weekOfYear=weekOffset;
weekstart=[calendar dateByAddingComponents:moveWeeks toDate:weekstart options:0];
//add 7 days
NSMutableArray* week=[NSMutableArray arrayWithCapacity:7];
for (int i=1; i<=7; i++) {
NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
compsToAdd.day=i;
NSDate *nextDate = [calendar dateByAddingComponents:compsToAdd toDate:weekstart options:0];
[week addObject:nextDate];
}
return [NSArray arrayWithArray:week];
}
If you want to get dates of next to next week from today, then pass weekOffset=2 like this:-
NSArray * allDatesOfNextToNextWeek = [self daysInWeek:2 fromDate:now];
If you want to get dates of previous week from today, then pass weekOffset=-1 like this:-
NSArray * allDatesOfPreviousWeek = [self daysInWeek:-1 fromDate:now];
Hope, this is what you're looking for. Any concern get back to me.

NSCalendar contains dedicated methods to do that for example nextDateAfterDate:matchingUnit:value:options: and dateByAddingComponents:toDate:options:
// Get the current calendar
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the next occurrence for the first weekday of the current calendar
NSDate *startOfNextWeek = [calendar nextDateAfterDate:[NSDate date] matchingUnit:NSCalendarUnitWeekday value:calendar.firstWeekday options:NSCalendarMatchStrictly];
// Create new date components +7 days and -1 seconds
NSDateComponents *endOfNextWeekComponents = [[NSDateComponents alloc] init];
endOfNextWeekComponents.day = 7;
endOfNextWeekComponents.second = -1;
// Add the date components to the start date to get the end date.
NSDate *endOfNextWeek = [calendar dateByAddingComponents:endOfNextWeekComponents toDate:startOfNextWeek options:NSCalendarMatchStrictly];
NSLog(#"%# - %#", startOfNextWeek, endOfNextWeek);

Related

Generate consecutive sequence of NSDates

Given some startDate, I would like to degenerate x number of consecutive days after this startDate. I'm attempting to use the following code:
// Generate dates
self.days = [[NSMutableArray alloc] init];
NSDate *startDate = [NSDate date];
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
for (int i = 1; i < self.mygoal.goalDays; i++) {
[self.days addObject:startDate];
startDate = [theCalendar dateByAddingComponents:dayComponent toDate:startDate options:0];
}
Question: Is the reassignment of startDate ok, given that I'm adding the same object to self.days?
Creating a sequence of dates is not as trivial as it sounds. Actually it is covered in the great WWDC2011 video «Performing Calendar Calculations».
You are adding in every loop a day to the last date. But actually this will fail in timezones with DST if the time is in the hour that is changed for the day of switching and for any following days as the dates will be nil.
If you instead change the date components i the loop and add it to the original satrtdate, it will only effect the day of DST-switching.
To also handle that you can set the hour of the start date to something safe — as noon — as all switches are performed at night hours.
With all this in mind I would use something like this to create a sequence of days with times set to start of day:
NSUInteger numberOfDays = 10;
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *startDate = [cal dateFromComponents:({
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.year = 2015;
comps.month = 1;
comps.day = 2;
comps.hour = 12; // for DST-safety
comps;
})];
NSMutableArray *dates = [#[] mutableCopy];
for (NSUInteger i =0 ; i < numberOfDays; ++i) {
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = i;
NSDate *date = [cal dateByAddingComponents:comps
toDate:startDate
options:0];
// set date to beginning of day
[cal rangeOfUnit:NSCalendarUnitDay
startDate:&date
interval:NULL
forDate:date];
[dates addObject:date];
}
So, yes, reassignment is technically OK, but in this particular case it is might cause unexpected trouble.
It's fine because you're not actually adding the same object. dateByAddingComponents: returns a new object, so when you assign it to startDate you are replacing the reference to your old object to a reference to the new one

adding current and future dates to an array

I am creating a custom type calendar and I am trying to see if it is possible to store dates in an array without statically assigning each one. For example the 1st date in the array would be the day it was first created and it would save the next week lets say into the relevant indexes in the array.
NSMutableArray *thisWeek = [today, tomorrow, sunday(Feb 24), monday (Feb 25), etc];
What would be the best way to go about storing the future dates?
NSMutableArray *days = [[NSMutableArray alloc] init];
NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *tempCop = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:[NSDate date]];
NSDate *today = [cal dateFromComponents:tempCop];
for (int i = 0; i < 8; i++)
{
NSDateComponents *comps = [[NSDateComponents alloc]init];
[comps setDay:i];
[days addObject:[cal dateByAddingComponents:comps toDate:today options:0]];
}
NSMutableArray *days;
days = [[NSMutableArray alloc] init];
NSDate *todayDate = [NSDate Date];
[days addObject:todayDate];
for (int i = 1; i <= 6; i++)
{
NSDate *newDate = [[NSDate date] dateByAddingTimeInterval:60*60*24*i];
[days addObject:newDate];
}
In this way, you can add days in array.
Take a look at dateByAddingTimeInterval: in the NSDate docs (link). It lets you add a given amount of seconds to a date.

How do I implement previous/next month buttons and show dates for current month?

Scenario:
I have an expense tracking iOS Application and I am storing expenses from a expense detail view controller into a table view (with fetched results controller) that shows the list of expenses along with the category and amount and date. I do have a date attribute in my entity "Money" which is a parent entity for either an expense or an income.
Question:
What I want is to basically categorize my expenses on a monthly basis and display it as the section header title for example : (Nov 1 - Nov 30,2012) and it shows expenses amount and related stuff according to that particular month. Two buttons are provided in that view, if I would press the right button, it will increment the month by a month (Dec 1 - Dec 31, 2012) and similarly the left button would decrement the month by a month.
How would I accomplish that? I am trying the following code - which is kinda working. Suppose I have my current section header as (Nov1 - Nov 30, 2012) and when I press the left button, it gives me the section header (Oct 1 - Oct 30, 2012) which is wrong, it should be Oct 31, 2012 and not Oct 30, 2012.
- (NSDate *)firstDateOfTheMonth
{
self.startDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:self.startDate];
[components setDay:1];
firstDateOfTheMonth = [[calendar dateFromComponents:components] retain];
return firstDateOfTheMonth;
}
- (NSDate *)lastDateOfTheMonth
{
NSCalendar* calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:firstDateOfTheMonth];
[components setMonth:[components month]+1];
[components setDay:0];
lastDateOfTheMonth = [[calendar dateFromComponents:components] retain];
return lastDateOfTheMonth;
}
Then I have a method called "monthCalculation" in which I call the above two methods.
- (void)monthCalculation
{
[self firstDateOfTheMonth];
[self lastDateOfTheMonth];
}
Now the following code when I press the left button (to decrement the month by a month):
- (IBAction)showPreviousDates:(id)sender
{
[self monthCalculation];
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setMonth:-1];
NSDate *newDate1 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:firstDateOfTheMonth options:0];
NSDate *newDate2 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:lastDateOfTheMonth options:0];
self.startDate = newDate1;
self.endDate = newDate2;
NSLog(#" self start date in previous mode =%#", self.startDate);
NSLog(#" self end date in previous mode =%#", self.endDate);
}
The following code when I press the right button (to increment the month by a month):
- (IBAction)showNextDates:(id)sender
{
[self monthCalculation];
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setMonth:1];
NSDate *newDate1 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:firstDateOfTheMonth options:0];
NSDate *newDate2 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:lastDateOfTheMonth options:0];
self.startDate = newDate1;
self.endDate = newDate2;
NSLog(#" self start date in previous mode =%#", self.startDate);
NSLog(#" self end date in previous mode =%#", self.endDate);
}
Am I doing it right? or there is a better way to do achieve this? Any help will be appreciated.
Here are some methods that should do what you want:
First, in your viewDidLoad method add:
self.startDate = [NSDate date];
[self updateDateRange];
This gives you a starting point. Then, I added the following five methods (Note: previousMonthButtonPressed/nextMonthButtonPressed should be wired up to your buttons):
// Return the first day of the month for the month that 'date' falls in:
- (NSDate *)firstDayOfMonthForDate:(NSDate *)date
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:date];
comps.day = 1;
return [cal dateFromComponents:comps];
}
// Return the last day of the month for the month that 'date' falls in:
- (NSDate *)lastDayOfMonthForDate:(NSDate *)date
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:date];
comps.month += 1;
comps.day = 0;
return [cal dateFromComponents:comps];
}
// Move the start date back one month
- (IBAction)previousMonthButtonPressed:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:self.startDate];
comps.month -= 1;
self.startDate = [cal dateFromComponents:comps];
[self updateDateRange];
}
// Move the start date forward one month
- (IBAction)nextMonthButtonPressed:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:self.startDate];
comps.month += 1;
self.startDate = [cal dateFromComponents:comps];
[self updateDateRange];
}
// Print the new range of dates.
- (void)updateDateRange
{
NSLog(#"First day of month: %#", [self firstDayOfMonthForDate:self.startDate]);
NSLog(#"Last day of month: %#", [self lastDayOfMonthForDate:self.startDate]);
}
Try this:
- (NSDate *)lastDateOfTheMonth
{
NSCalendar* calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:firstDateOfTheMonth];
[components setMonth:[components month]+1];
NSDateComponents* offset = [[[NSDateComponents alloc] init] retain];
[offset setDay:-1];
lastDateOfTheMonth = [[calendar dateByAddingComponents:offset toDate:[components date] options:0] retain];
return lastDateOfTheMonth;
}

Get only weekends between two dates

I'm trying get only the Saturdays and Sundays between two dates, but I don't know why get me free days on a week.
Here is my code:
- (BOOL)checkForWeekend:(NSDate *)aDate {
BOOL isWeekendDate = NO;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSRange weekdayRange = [calendar maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:aDate];
NSUInteger weekdayOfDate = [components weekday];
if (weekdayOfDate == weekdayRange.location || weekdayOfDate == weekdayRange.length) {
// The date falls somewhere on the first or last days of the week.
isWeekendDate = YES;
}
return isWeekendDate;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSString *strDateIni = [NSString stringWithString:#"28-01-2012"];
NSString *strDateEnd = [NSString stringWithString:#"31-01-2012"];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd-MM-yyyy"];
NSDate *startDate = [df dateFromString:strDateIni];
NSDate *endDate = [df dateFromString:strDateEnd];
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
// int months = [comps month];
int days = [comps day];
for (int i=0; i<days; i++)
{
NSTimeInterval interval = i;
NSDate * futureDate = [startDate dateByAddingTimeInterval:interval];
BOOL isWeekend = [self checkForWeekend:futureDate]; // Any date can be passed here.
if (isWeekend) {
NSLog(#"Weekend date! Yay!");
}
else
{
NSLog(#"Not is Weekend");
}
}
}
The problem:
The issue was caused by NSTimeInterval interval = i; The logic of the for loop was to iterate by days. Setting the time interval to i was iterating by seconds.
From documentation on NSTimeInterval
NSTimeInterval is always specified in seconds;
The answer:
Changing the NSTimeInterval line to
NSTimeInterval interval = i*24*60*60;
Here is a link to another answer I posted on SO (shameless, I know). It has some code that may help you with dates in the future. The methods are implemented as categories of NSDate, meaning they become methods of NSDate.
There are several functions there that help with weekends. But these two might be most helpful:
- (NSDate*) theFollowingWeekend;
- (NSDate *) thePreviousWeekend;
They return the date of the weekend following and prior to the receiver (self).
Generally, you should not use the notion that a day is 86400 seconds, and should use NSDateComponents and NSCalendar. This works even when daylight savings time transitions occur between dates. Like this:
- (NSDate *) dateByAddingDays:(NSInteger) numberOfDays {
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = numberOfDays;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
return [theCalendar dateByAddingComponents:dayComponent toDate:self options:0];
}
One very important thing to remember is that one day is not (necessarily) equal to 24*60*60 seconds. And you should not do date arithmetic yourself
What you really need to do might seem a little tedious but this is the correct thing to do: use NSCalendar and – dateByAddingComponents:toDate:options:
See Calendrical Calculations guide.

iPhone NSDate eg. next Friday

I want to create a function which results the date of next Friday but I have no plan how to do it. Has anyone a good hint to me ?
E.g. Get current date using NSDate, then use 'components>fromDate:' from NSCalendar to get the NSDateComponents, then add the time difference to next Friday and create a new NSDate and Bob's is your uncle.
Here is my working solution for getting the next 5 Sundays in Gregorian calendar:
self.nextBeginDates = [NSMutableArray array];
NSDateComponents *weekdayComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int currentWeekday = [weekdayComponents weekday]; //[1;7] ... 1 is sunday, 7 is saturday in gregorian calendar
NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setDay:8 - currentWeekday]; // add some days so it will become sunday
// build weeks array
int weeksCount = 5;
for (int i = 0; i < weeksCount; i++) {
[comp setWeek:i]; // add weeks
[nextBeginDates addObject:[[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:[NSDate date] options:0]];
}
[comp release];
This should work
+ (NSDate *) dateForNextWeekday: (NSInteger)weekday {
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
fromDate:today];
/*
Add components to get to the weekday we want
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
NSInteger dif = weekday-weekdayComponents.weekday;
if (dif<=0) dif += 7;
[componentsToSubtract setDay:dif];
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract
toDate:today options:0];
return beginningOfWeek;
}
Keep it simple, safe, and readable! (....KISSAR?)
#define FRIDAY 6
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
NSDate *nextFriday = [NSDate date];
NSInteger iWeekday = [[gregorian components:NSWeekdayCalendarUnit fromDate:nextFriday] weekday];
while (iWeekday != FRIDAY) {
nextFriday = [gregorian dateByAddingComponents:dayComponent toDate:nextFriday options:0];
iWeekday = [[gregorian components:NSWeekdayCalendarUnit fromDate:nextFriday] weekday];
}
Now nextFriday has your date.
Hope this helps!
EDIT
Note that if the current date was already a Friday, it would return that instead of the next Friday. If that's undesirable just init your nextFriday to a day later (so if current date was a Friday, it would start on Saturday, forcing the next Friday. And if current date was a Thursday you'd automatically have your next Friday without needing the loop).
Here is my solution, and just to warn you, on a saturday is the friday before shown.
cheers to all
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
int weekday = [weekdayComponents weekday];
int iOffsetToFryday = -weekday + 6;
weekdayComponents.weekday = iOffsetToFryday;
NSDate *nextFriday = [[NSCalendar currentCalendar] dateByAddingComponents:weekdayComponents toDate:today options:0];