ios - How do I split the current time into 3 strings; hours, minutes, and seconds -
i'm making clock app, , want display current time, components (hours minutes, seconds) spaced out. think way separate time 3 strings. how do that?
- (void)updatetime { [updatetimer invalidate]; updatetimer = nil; currenttime = [nsdate date]; nsdateformatter *timeformatter = [[nsdateformatter alloc] init]; [timeformatter settimestyle:nsdateformattermediumstyle]; lbltime.text = [timeformatter stringfromdate:currenttime]; updatetimer = [nstimer scheduledtimerwithtimeinterval:0.01 target:self selector:@selector(updatetime) userinfo:nil repeats:yes]; }
a couple things here:
1 ) if want running timer, don't invalidate each time "updatetime
" called (and call scheduledtimerwithtimeinterval:
once... instead of @ end of each time "updatetime
" called).
2 ) looks have single label displaying time. should make timeformatter
ivar (instance variable, it's created , set once) , can set format via:
timeformatter.dateformat = @"hh:mm:ss";
and should set.
your new updatetime
method this:
- (void)updatetime { currenttime = [nsdate date]; lbltime.text = [timeformatter stringfromdate:currenttime]; }
3 ) if want 3 different labels, need declare iboutlets 3 labels , have 3 different date formatters. example:
@interface yourviewcontroller : uiviewcontroller () { iboutlet uilabel * hourlabel; // need connect these in xib/storyboard iboutlet uilabel * minutelabel; iboutlet uilabel * secondlabel; nsdateformatter * hourformatter; nsdateformatter * minuteformatter; nsdateformatter * secondformatter; }
then, in "viewdidload:
" method, set formatters:
hourformatter = [[nsdateformatter alloc] init; hourformatter.dateformatter = @"hh"; minuteformatter = [[nsdateformatter alloc] init; minuteformatter.dateformatter = @"mm"; secondformatter = [[nsdateformatter alloc] init; secondformatter.dateformatter = @"ss";
and finally, in "updatetime
" method:
- (void)updatetime { currenttime = [nsdate date]; if(hourformatter) { if(hourlabel) { hourlabel.text = [hourformatter stringfromdate: currenttime]; } else { nslog( @"you need connect hourlabel outlet in storyboard or xib" ); } } else { nslog( @"you need allocate , init , set hourformatter"); } minutelabel.text = [minuteformatter stringfromdate: currenttime]; secondlabel.text = [secondformatter stringfromdate: currenttime]; }
Comments
Post a Comment