iphone - NSDate best practice in creating a date with no time element -
i writing app uses core-data store data. included in date field of interested in date not time. need select records based on date (not time) , have created category on nsdate return date, normalised set time follows:
+ (nsdate *)datewithnotime:(nsdate *)datetime { if( datetime == nil ) { datetime = [nsdate date]; } nsdatecomponents* comps = [[nscalendar currentcalendar] components:nsyearcalendarunit|nsmonthcalendarunit|nsdaycalendarunit fromdate:datetime]; nsdate *dateonly = [[nscalendar currentcalendar] datefromcomponents:comps]; [dateonly datebyaddingtimeinterval:(60.0 * 60.0 * 12.0)]; // push middle of day. return dateonly;
}
i use when add data core-data store (i have setter uses method set primitive date value) , use method create date use compare dates when performing fetch request. in theory should work - ie pick out dates i'm looking for.
i'm nervous though i'm not totally sure effect changing time-zone or locale have. still work ?
what considered best practice when storing , searching on date when aren't interested in time.
cheers.
edit
after reading discussion recommended think should modify code follows. thinking being if ensure push specific calendar system , specific timezone (utc) dates should same regardless of when set date , when read date. comments on new code appreciated.
+ (nsdate *)datewithnotime:(nsdate *)datetime { if( datetime == nil ) { datetime = [nsdate date]; } nscalendar *calendar = [[[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar] autorelease]; [calendar settimezone:[nstimezone timezonewithabbreviation:@"utc"]]; nsdatecomponents *components = [[[nsdatecomponents alloc] init] autorelease]; components = [calendar components:nsyearcalendarunit|nsmonthcalendarunit|nsdaycalendarunit fromdate:datetime]; nsdate *dateonly = [calendar datefromcomponents:components]; [dateonly datebyaddingtimeinterval:(60.0 * 60.0 * 12.0)]; // push middle of day. return dateonly;
}
you have few issues deal here. first, noted, timezones. need worry daylight savings, change concept of “midday.”
take @ this discussion on cocoadev apple engineer gives answers , discusses best practices.
Comments
Post a Comment