0

I'm trying to figure out how to create a NSDate that is set to the end of the year. ie 2013, I found a method that you can get the time since 1970 by adding the amount of seconds. I don't see this working because cal the seconds would have to take in leap years.

I found the following code to set a NSDateComponents to the end of the year.

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:2012];
    [comps setMonth:12];
    [comps setDay:11];

    [comps setHour:0];
    [comps setMinute:0];
    [comps setSecond:0];

is there a way to get a NSDate from this? What I'm trying to do is get the amount of time until the end of the year by using

NSDateComponents *timeDifference = [[NSCalendar currentCalendar] 
                                        components:  NSMonthCalendarUnit| NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit  fromDate:[NSDate date] toDate:comps options:0];

which needs a NSDate for the end date.

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
Ted pottel
  • 6,869
  • 21
  • 75
  • 134

2 Answers2

3

Yes, there is.

Use

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *newDate = [calendar dateFromComponents:comps];

You can change the calender identifier as per your requirement.

Please refer this link for details.

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
1

Heres some code that may point you in the right direction.

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2012];
[comps setMonth:12];
[comps setDay:11];

[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];

NSDate *myDate = [[NSCalendar currentCalendar] dateFromComponents:comps];