ios - Trying to use NSDate for time only -
i'm struggling find way use nsdate time purposes. trying following code:
- (void)awakefrominsert { nsdatecomponents *comps = [[nsdatecomponents alloc] init]; comps.minute = 45; comps.second = 0; nscalendar *calendar = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar]; self.periodduration = [calendar datefromcomponents:comps]; nslog(@"periodduration: %@",self.periodduration); comps = [[nsdatecomponents alloc] init]; comps.hour = 8; comps.minute = 0; self.firstperiodstarttime = [calendar datefromcomponents:comps]; nslog(@"firstperiodtime: %@",self.periodduration); }
but result is:
periodduration: 0001-12-31 22:24:04 +0000 firstperiodtime: 0001-12-31 22:24:04 +0000
the result expecting:
periodduration: 45:00 firstperiodtime: 08:00
what doing wrong? how can fix this? thank you.
the log of date misleading you, if forming date few components not proper date instance uniquely identifies date , time.
if try code snipped can find if converting dates string expect
nsdatecomponents *comps = [[nsdatecomponents alloc] init]; comps.minute = 45; comps.second = 0; nscalendar *calendar = [nscalendar currentcalendar]; nsdate *perioddate = [calendar datefromcomponents:comps]; nsdateformatter *dateformatter = [[nsdateformatter alloc] init]; [dateformatter setdateformat:@"mm:ss"]; nslog(@"periodduration: %@",[dateformatter stringfromdate:perioddate]); comps = [[nsdatecomponents alloc] init]; comps.hour = 8; comps.minute = 0; nsdate *firstperioddate = [calendar datefromcomponents:comps]; [dateformatter setdateformat:@"hh:mm"]; nslog(@"firstperiodtime: %@",[dateformatter stringfromdate:firstperioddate]);
periodduration: 45:00
firstperiodtime: 08:00
Comments
Post a Comment