Calculate Year From current NSDate - iphone

I want to calculate the year from current NSDate. Suppose my current date 14-06-2012 so, what would be last date after end of year. (In simple way I can explain you that, if I have date 01-01-2012 then after end of year I would get 31-12-2012). So, how do I calculate year form current date.
Following output I expect for my project:
Next or End year Date where year end (Like 31-12-2012).
Next or end year month (Last date month).
Next or end year (Last date year or next year).
It Should be NSDate format. Hope you would able to understand my point.

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:(NSYearCalendarUnit) fromDate:today];
[comps setDay:31]; // last day of year is always the same
[comps setMonth:12];
NSInteger year = [comps year]; // the current year
NSDate *lastDayOfYear = [gregorian dateFromComponents:comps]; // the last day of the year

You can use this:
NSDate *now = [NSDate date];
NSDateComponents *dc = [[NSDateComponents alloc] init];
[dc setYear:1];
NSDate *targetDateObject = [[NSCalendar currentCalendar] dateByAddingComponents:dc toDate:now options:0];
[dc release];

Related

How to get start date and end date of a week in ios [duplicate]

This question already has answers here:
Current Week Start and End Date
(18 answers)
Closed 6 years ago.
please have a look to following lines of code:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger weekNumber = [[calendar components: NSWeekCalendarUnit fromDate:date] week];
now how we can get the first and last day of the given week number (assume that the week starts from monday to sunday).
also if it possible to get the array of all the dates belongs to the same week number.
To get the first day of the week the following code can be used.
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger weekNumber = [[calendar components: NSWeekCalendarUnit fromDate:now] week];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now];
[comp setWeek:weekNumber]; //Week number.
[comp setWeekday:1]; //First day of the week. Change it to 7 to get the last date of the week
NSDate *resultDate = [gregorian dateFromComponents:comp];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM d, yyyy"];
NSString *myDateString = [formatter stringFromDate:resultDate];
NSLog(#"%#",myDateString);
as commented in the above code change the parameter of setWeekday method to 7 to get the last day of the week.
Once u have the first day and last day of the week u can get all the dates as mentioned in the below link.
Array for dates between two dates
Note: The week starts from Monday for the region setting UK.
To change the iPhone Calendar to show Monday as the first day of the week.
1. tap "Settings"
2. tap "General"
3. tap "International"
4. tap "Region Format"
5. select "united kingdom"

Get first and last day of week for a couple of weeks

I need to make a calendar in which the user can scroll between several weeks. The first and last day of the week will be displayed like (e.g.) "June 4 - June 10".
Now I knew from the beginning that I'd need NSDate and NSCalendar, and indeed I managed to get the first and last day of just thist week, but it looks extremely cumbersome and I am sure there needs to be an easier method, as I need to get the dates for several more coming and past weeks.
This is my code which gives the day and month of the first and last day of the current week:
NSDate *today = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSYearCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit) fromDate:[NSDate date]];
NSDate *beginOfWeek = [today dateByAddingTimeInterval: -1*([comp weekday]-2)*24*3600];
NSDate *endOfWeek = [today dateByAddingTimeInterval:(7-[comp weekday]+2)*24*3600];
NSLog(#"beginWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] day]);
NSLog(#"endWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] day]);
NSLog(#"beginWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] month]);
NSLog(#"endWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] month]);
I found this, which may be helpful to you: http://www.cocoanetics.com/2009/11/add-one-week-skip-weekend/
- (NSDate *)addWeekToDateAndSkipWeekend:(NSDate *)now {
int daysToAdd = 6; // we'll add the 7th later
// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];
// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate = [gregorian dateByAddingComponents:components toDate:now options:0];
[components setDay:1]; // reuse to skip single days
NSDateComponents *newDateComps; // new componets to get weekday
// do always executed once, so we add the 7th day here
do
{
// add one day
newDate = [gregorian dateByAddingComponents:components toDate:newDate options:0];
newDateComps = [gregorian components:NSWeekdayCalendarUnit fromDate:newDate];
// repeat if the date is Saturday (7) or Sunday (1)
NSLog(#"weekday: %d", [newDateComps weekday]);
} while (([newDateComps weekday]==7)||([newDateComps weekday]==1));
return newDate;
}
Theoretically, you run this in a for loop with [NSDate date] and you will get the 7th day returned, you would then run the returned 7th day through this and get the next..etc..
May need minor alteration, to remove the check for Saturday+Sunday if you don't need it.
Hope this helps !

NSDate - Getting Days of the Month (Not Days of the year)?

Using NSDateComponents I know how to get the day component, but this gives me a value from 1 - 365, right? I need to get the days 1-30 of a specific month, how can I?
For example, I have an NSDate which might be 16th May. I want to be able to get the day, so it returns 16. Being the 16th day of that month (not the 16th day of the year).
Thanks.
EDIT:
I have this:
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [cal components:NSDayCalendarUnit fromDate:[[NSUserDefaults standardUserDefaults] objectForKey:#"dateSaved"]];
However comps.day returns 1 when it should equal what the date is saved as, say 4.
The day value of NSDateComponents gives you the day of month according to the given calendar:
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSDayCalendarUnit fromDate:date];
NSLog(#"%# / %d", date, comps.day);
gives
2012-02-04 15:27:36.682 testapp[1533:f803] 2012-02-04 14:27:36 +0000 / 4
although February, 4th would be the 35th day of the year.

How can we get Next Date From Entered Date based on given repeate period ?

I am new to iPhone.
I want to find out the next date from given date based on repeat period.
For example :
I want function as follows ...
given date : 31'May 2011 and Repeat : Monthly given as argument then the next date should be returned 31'July 2011 (as June don't have 31st day)
And function should be smart enough to to calculate next leap year day also, if given date : 29'Feb 2008 and Repeat : Yearly given as argument then the next date should be returned 29'Feb 2012 (The next leap year day)
And so on repeat option can be one of these : Daily, Weekly(On selected day of week), Monthly, Yearly, None(No repeat at all)
// start by retrieving day, weekday, month and year components for yourDate
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) yourDate];
NSInteger theDay = [todayComponents day];
NSInteger theMonth = [todayComponents month];
NSInteger theYear = [todayComponents year];
// now build a NSDate object for yourDate using these components
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:theDay];
[components setMonth:theMonth];
[components setYear:theYear];
NSDate *thisDate = [gregorian dateFromComponents:components];
[components release];
// now build a NSDate object for the next day
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: yourDate options:0];
[offsetComponents release];
[gregorian release];
This is copied from How can i get next date using NSDate? and the credit goes to #Massimo Cafaro for this answer.
To get tomorrow's date use the dateByAddingTimeInterval method.
// Start with today
NSDate *today = [NSDate date];
// Add on the number of seconds in a day
NSTimeInterval oneDay = 60 * 60 * 24;
NSDate *tomorrow = [today dateByAddingTimeInterval:oneDay];
It's pretty simple to extend that to a week etc
NSTimeInterval oneWeek = oneDay * 7;
NSDate *nextWeek = [today dateByAddingTimeInterval:oneWeek];
try this :-
- (NSDate *)dateFromDaysOffset:(NSInteger)daysOffset
{
// start by retrieving day, weekday, month and year components for yourDate
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:daysOffset];
NSDate *offsetDate = [gregorian dateByAddingComponents:offsetComponents toDate:self options:0];
[offsetComponents release];
[gregorian release];
return offsetDate;
}

NSDate month addition and subtraction

I have a class that holds an start date and an end date, normally initialised to the firt and last second of the month.
The following function works correctly going from Nov 2010 forwards into December and back again however going backwards from November ends up with startDate set to
2010-09-30 23:00:00 GMT
Ie. a month and an hour ago.
Strangely the endDate is still correctly set to
2010-11-01 00:00:00 GMT
And going forward a month from this incorrect date also results in the correct time and date.
Is this a bug or am I doing something I shouldn't be ?
-(void) moveMonth:(NSInteger)byAmount { // Positive or negative number of months
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
// Update the start date
[components setMonth:byAmount];
NSDate *newStartDate = [cal dateByAddingComponents:components toDate:[self startDate] options:0];
[self setStartDate:newStartDate];
// And the end date
[components setMonth:1];
NSDate *newEndDate = [cal dateByAddingComponents:components toDate:[self startDate] options:0 ];
[self setEndDate:newEndDate];
}
SOLUTION: Answer correctly pointed out this is a DST issue
If you want to deal in absolute times and date then using the following avoids any DST being involved.
NSCalendar *cal = [[NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSTimeZone *zone = [NSTimeZone timeZoneWithName:#"GMT"];
[cal setTimeZone:zone];
It is probably not a bug but something related to DST changes in October-November period.
It would be easier to just grab the month and year of the current date, add/subtract the number of months difference, then generate a date from those new values. No need to worry about Daylight Saving changes, leap years, etc. Something like this ought to work:
-(void) moveMonth:(NSInteger)byAmount {
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
// we're just interested in the month and year components
NSDateComponents *nowComps = [cal components:(NSYearCalendarUnit|NSMonthCalendarUnit)
fromDate:now];
NSInteger month = [nowComps month];
NSInteger year = [nowComps year];
// now calculate the new month and year values
NSInteger newMonth = month + byAmount;
// deal with overflow/underflow
NSInteger newYear = year + newMonth / 12;
newMonth = newMonth % 12;
// month is 1-based, so if we've ended up with the 0th month,
// make it the 12th month of the previous year
if (newMonth == 0) {
newMonth = 12;
newYear = newYear - 1;
}
NSDateComponents *newStartDateComps = [[NSDateComponents alloc] init];
[newStartDateComps setYear: year];
[newStartDateComps setMonth: month];
[self setStartDate:[cal dateFromComponents:newDateComps]];
[newDateComps release];
// Calculate newEndDate in a similar fashion, calling setMinutes:59,
// setHour:23, setSeconds:59 on the NSDateComponents object if you
// want the last second of the day
}
Here is a way to do it properly. This method returns a new NSDate after adding/subtracting month "byAmount".
-(NSDate*) moveMonth:(NSInteger)byAmount {
NSDate *now = [NSDate date];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setMonth:byAmount];
NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:now options:0];
return newDate;
}