Olex
Olex

Reputation: 1656

NSDate. Creating new date with same time

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

Answers (3)

hatunike
hatunike

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

Stephen Darlington
Stephen Darlington

Reputation: 52565

You've already outlines all the bits you need:

  1. Convert your NSDate to its components using NSDateComponents
  2. Get the hours/minutes/seconds
  3. Covert your new date to its components
  4. Set tehe hours/minutes/seconds to the values you saved in step 2
  5. Convert it back to a date again

Upvotes: 1

Catfish_Man
Catfish_Man

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

Related Questions