Set time on existing NSDate object

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

  1. goedsole macrumors newbie

    Joined:
    Apr 21, 2010
    #1
    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

    lee1210

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

    Code:
    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.

    -Lee

    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:
    Code:
    NSCalendar *gregorian = [[NSCalendar alloc]
        initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comp = [gregorian components:  (NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate: myDate];
    NSDate *myNewDate = [gregorian dateFromComponents:comps];
    [comps release];
    [gregorian release];
    
     
  3. goedsole thread starter macrumors newbie

    Joined:
    Apr 21, 2010

Share This Page