revolutionkpi revolutionkpi - 1 year ago 88
iOS Question

Change year, month and day of NSDate object

in my iPhone application I have a start date of event, for exemple: 2013-05-17 15:00:12 +0000. My question is, how can I change 2013-05-17 with today date, but leave time the same?

Answer Source

You need to gather the date components and amend the required properties.

//gather current calendar
NSCalendar *calendar = [NSCalendar currentCalendar];

//gather date components from date
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:[NSDate date]];

//set date components
[dateComponents setDay:17];
[dateComponents setMonth:5];
[dateComponents setYear:2013];

//save date relative from date
NSDate *date = [calendar dateFromComponents:dateComponents];

Either that, or you could add the number of seconds in 1 day to increment the value:

NSDate *date = [NSDate dateWithTimeInterval:((60 * 60) * 24) sinceDate:[NSDate date]];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download