Reputation: 1656
I have existing NSDate
object what represents date and time of event. My task is to make copying function of existing event to other date with all attributes except day and month(but with saving of hours and minutes). I see NSDate
documentation but here is no direct method for this. I can add few days with standard methods or NSDateComponents
but new date will be set with calendar, not with adding or substracting quantity days.
Is it a right way to extract "HH:mm" string from previous date, set it into formatted string and then convert it into new NSDate?
Upvotes: 0
Views: 533
Reputation: 1977
The other answers are already sufficient, but here is my implementation using the other answers as a guide.
+ (NSDate*)useSameTimeAsDate:(NSDate*)priorDate butOnADifferentDate:(NSDate*)differentDate
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *priorComponents = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:priorDate];
NSDateComponents *newComponents = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:differentDate];
[newComponents setSecond:[priorComponents second]];
[newComponents setMinute:[priorComponents minute]];
[newComponents setHour:[priorComponents hour]];
return [cal dateFromComponents:newComponents];
}
Upvotes: 1
Reputation: 52565
You've already outlines all the bits you need:
Upvotes: 1
Reputation: 41801
Converting to and from a string is probably not the best way. My suggestion would be to make an NSDateComponents from the date. Then you can set the month and day directly, and convert back to a date.
Upvotes: 4