如何以000:00:00:00格式显示NSDate倒计时?

时间:2012-01-22 20:17:05

标签: ios nsdate nsdateformatter nsdatecomponents

我目前有以下代码来显示特定日期的倒计时:

NSDate *date=[NSDate date];
int secondsNow=(int)[date timeIntervalSince1970];
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
NSString *LaunchBegin=[NSString stringWithFormat:@"20120126"]; // ENTER THE DATE OF LAUNCH HERE IN FORMAT YYYYMMDD
[formatter setDateFormat:@"yyyyMMdd"];
NSDate *otherDate=[formatter dateFromString:LaunchBegin];
int secondsTarget=(int)[otherDate timeIntervalSince1970];
int differenceSeconds=secondsTarget-secondsNow;
int days=(int)((double)differenceSeconds/(3600.0*24.00));
int diffDay=differenceSeconds-(days*3600*24);
int hours=(int)((double)diffDay/3600.00);
int diffMin=diffDay-(hours*3600);
int minutes=(int)(diffMin/60.0);
int seconds=diffMin-(minutes*60);

CountdownLabel.text=[NSString stringWithFormat:@"%d:%d:%d:%d",days,hours,minutes,seconds]; // This is what I want to change to 000:00:00:00

NSTimer *timer;

timer = [NSTimer scheduledTimerWithTimeInterval: 0.8
                                         target: self
                                       selector: @selector(updateTimeToLaunch)
                                       userInfo: nil
                                        repeats: NO];

if(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0)
{

    UIImage *image = [UIImage imageNamed: @"end_countdown_highres.png"];
    [backing setImage:image];

    [facebook setHidden:NO];
    [twitter setHidden:NO];

}

如何以“000:00:00:00”格式而不是当前的“0:0:0:0”格式输出?

1 个答案:

答案 0 :(得分:-1)

[NSString stringWithFormat:@"%03d:%02d:%02d:%02d",days,hours,minutes,seconds];