1

I have a UIDatePicker and a UILabel to display the chosen date. Right now, the date is displayed as '2013-8-30 10:30:54 +0000'. I would like the date to instead be displayed as '00:00:00:00' in the order 'dd:hh:mm:ss. Then I would like to initiate a timer from an IBAction that begins counting down from the chosen date in the display for 'dd:hh:mm:ss'. any help or reference code that I could analyze would be greatly appreciated. I'm new and completely self taught. Thanks in advance. Cheers!

@synthesize picker;
@synthesize label;

-(IBAction)displayDate:(id)sender {
    NSDate *selected = [picker date];
    NSString *date = [selected description];
    self.label.text = date;
}

- (void)viewDidLoad {
    NSDate *now = [NSDate date];
    [picker setDate:now animated:YES];
    self.label.text = [now description];
}
@end
4

1 回答 1

0

第一的:

要以您想要的格式显示日期,只需使用NSDateFormatter,如下例所示:

self.formatter = [NSDateFormatter new]; //save a property of NSDateFormatter type, you'll use this before
[formatter setDateFormat:@"dd:HH:mm:ss"];

self.date = [NSDate date]; //save in a property, this will be your start date
self.label.text = [formatter stringFromDate:self.date];

第二:

要执行类似倒计时的行为,您可以从日期中减去一秒(或更多,取决于您想要什么),再次将新日期转换为字符串并更新您的标签。下面是你将如何做到这一点:

在某处设置一个 NSTimer:

[NSTimer scheduledTimerWithTimeInterval:1.0
                                 target:self
                               selector:@selector(refreshLabel)
                               userInfo:nil
                                repeats:YES];

并实现方法refreshLabel

-(void)refreshLabel
{
    NSDate *dateCountDown = [NSDate dateWithTimeIntervalSince1970:[self.date timeIntervalSince1970] - 1]; //the start-up date minus 1 sec.
    self.label.text = [formatter stringFromDate:dateCountDown];
    self.date = dateCountDown;
}
于 2013-08-31T00:02:28.677 回答