1. 程式人生 > >IOS倒計時相關程式碼

IOS倒計時相關程式碼

程式碼

NSDate *destinationDate=[nowDate dateByAddingTimeInterval:[dataModel.countdowntimefloatValue]];

components=[calendar components:unitFlags fromDate:destinationDate];

counterDownTimer=[NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(timeDownDownMethod:) userInfo:nilrepeats:YES

];

                    [[NSRunLoopmainRunLoop] addTimer:counterDownTimerforMode:NSDefaultRunLoopMode];

                    [counterDownTimerfire];

其中destinationDate 為目標日期

timeDownDownMethod:方法

-(void)timeDownDownMethod:(NSTimer*)timer

{

NSCalendar *calendar = [NSCalendarcurrentCalendar];

NSDate *fireDate = [calendar

dateFromComponents:components];//目標時間

NSDate *today = [NSDatedate];//當前時間

unsignedint unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *d = [calendar components:unitFlags fromDate:today toDate:fireDate

options:0];//計算時間差

   

NSString * day,*hour,*minute,*second;

        day=[NSStringstringWithFormat:@"%ld",(long)[d day]];

        hour=[NSStringstringWithFormat:@"%ld",(long)[d hour]];

        minute=[NSStringstringWithFormat:@"%ld",(long)[d minute]];

        second=[NSStringstringWithFormat:@"%ld",(long)[d second]];

if (day.length==1){

            day=[NSStringstringWithFormat:@"0%ld",(long)[d day]];

        }if (hour.length==1)

        {

            hour=[NSStringstringWithFormat:@"0%ld",(long)[d hour]];

        }if (minute.length==1)

        {

            minute=[NSStringstringWithFormat:@"0%ld",(long)[d minute]];

        }if(second.length==1)

        {

            second=[NSStringstringWithFormat:@"0%ld",(long)[d second]];

        }

timeLabel.text = [NSStringstringWithFormat:@"%@%@小時%@%@",day, hour,minute,second];//倒計時顯示

timeString=timeLabel.text;

}