Set time on existing NSDate object

Discussion in 'Mac Programming' started by goedsole, Apr 21, 2010.

  1. goedsole macrumors newbie

    Apr 21, 2010
    Dear Y'all -

    I've got an NSDate object and want to change it's value to a hard-coded time (12:00am) while leaving the date as is. This doesn't seem like it would be hard, but experimenting and searching have not helped.

    Any help is appreciated.

    - Billy
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    NSDate is immutable, so you'll need to create a new one, you can't alter one you already have.

    NSTimeInterval oldInterval = [myDate timeIntervalSinceReferenceDate];
    double secondsSinceMidnight = fmod(oldInterval,86400.0);
    NSDate *myNewDate = [NSDate dateWithTimeIntervalSinceReferenceDate:(oldInterval - secondsSinceMidnight)];
    Assuming the date you want to "modify" is myDate, i think this should do it. I haven't tested this at all.


    EDIT: You could also get a new date by getting the seconds since midnight as a negative number, then send dateByAddingTimeInterval: to your original date with the negative seconds as your parameter.

    EDIT 2: It may be easier to use NSCalendar:
    NSCalendar *gregorian = [[NSCalendar alloc]
    NSDateComponents *comp = [gregorian components:  (NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate: myDate];
    NSDate *myNewDate = [gregorian dateFromComponents:comps];
    [comps release];
    [gregorian release];
  3. goedsole thread starter macrumors newbie

    Apr 21, 2010

Share This Page