在xcode中分隔小时,分钟和秒

时间:2012-10-04 05:41:20

标签: iphone ios xcode ipad

我创建了一个闹钟应用程序。 其中,当用户单击“设置计时器”按钮时,将调用Picker视图。 Picker视图显示小时,分钟和秒。 当用户选择它们并单击“确定”时,则“更改定时器按钮值”。

例如: 如果用户选择2小时,4分钟和10秒,则

按钮标签将是02:04:10

现在我要分开所有3个东西,例如2个将存储在一个字符串中,4个将存储在其他字符串中,10个存储在其他字符串中。

我该怎么办? 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

试试这个想想可能对你有所帮助....

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"<your date format goes here"];
NSDate *Yourcurrenttime = [dateFormatter dateFromString:string1];



    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [calendar components:(NSHourCalendarUnit |NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: Yourcurrenttime];

    NSInteger hour = [components hour];
    NSInteger minutes = [components minute];
    NSInteger seconds = [components second];

并将所有值存储在字符串中。

NSString *HourSTR =[NSString stringWithFormat:@"%d",hour];
NSString *minutesSTR =[NSString stringWithFormat:@"%d",minutes];
NSString *secondsSTR =[NSString stringWithFormat:@"%d",seconds];

答案 1 :(得分:2)

我完成了一次倒计时这样的倒计时器可能对你有用

 -(void) viewWillAppear:(BOOL)animated
 {
 timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
 }

 -(void) updateCountdown 
 {

NSString *dateString = @"14-09-2012";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];


NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];



NSDateComponents *componentsHours = [calendar components:NSHourCalendarUnit fromDate:now];
NSDateComponents *componentMint = [calendar components:NSMinuteCalendarUnit fromDate:now];    
NSDateComponents *componentSec = [calendar components:NSSecondCalendarUnit fromDate:now];        


NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsDaysDiff = [gregorianCalendar components:NSDayCalendarUnit
                                                            fromDate:now
                                                              toDate:dateFromString
                                                             options:0];



lblDaysSetting.text=[NSString stringWithFormat:@"%02d",componentsDaysDiff.day];
lblHouresSetting.text=[NSString stringWithFormat:@"%02d",(24-componentsHours.hour)];    
lblMinitSetting.text=[NSString stringWithFormat:@"%02d",(60-componentMint.minute)];  
lblSecSetting.text=[NSString stringWithFormat:@"%02d",(60-componentSec.second)];  



 }

现在只需设置你的逻辑