Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

goedsole

macrumors newbie
Original poster
Apr 21, 2010
9
0
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
 
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];
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.