【非凡程序員】 OC第十六節課 初識IOS開發三 (午夜十二點倒計時)

計算從如今開始到午夜十二點的時間,先算出 如今和午夜十二點的時間戳的差,這是一個秒數,再把他轉換爲小時分鐘。atom

 

ViewController.h文件:spa

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
orm

@property (weak, nonatomic) IBOutlet UITextField *now;
@property (weak, nonatomic) IBOutlet UITextField *wuye;
@property (nonatomic,strong) NSTimer *timer;
get

@endstring

 

ViewController.m文件:
#import "ViewController.h"it

@interface ViewController ()io

@endform

@implementation ViewControllerimport

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _timer=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(date) userInfo:nil repeats:YES];
}
date

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) date
{
    NSDate *now=[NSDate date];
    NSDateFormatter *former=[NSDateFormatter new];
    [former setDateFormat:@"yyyy年MM月dd日HH時mm分ss秒"];
    NSString *str=[former stringFromDate:now]; //把時間類型轉換爲NSString類型
    _now.text=str;

    NSString *timeSp1 = [NSString stringWithFormat:@"%li", (long)[now timeIntervalSince1970]];
    NSLog(@"timeSp:%@",timeSp1); //時間戳的值   (重點)

    NSString* timeStr = @"2015-06-12 00:00:00";
    NSDateFormatter *formatter = [NSDateFormatter new] ;
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate* date = [formatter dateFromString:timeStr]; //把NSString類型轉換爲時間類型

    NSString *timeSp2 = [NSString stringWithFormat:@"%li", (long)[date timeIntervalSince1970]];
    NSLog(@"timeSp:%@",timeSp2); //時間戳的值
   
    int timeSp=[timeSp2 intValue]-[timeSp1 intValue];
    int miao=timeSp%60;
    int xiaoshi=(timeSp/60)/60;
    int fenzhong=(timeSp/60)%60;
    [_wuye setText:[NSString stringWithFormat:@"%i時 %i分 %i秒",xiaoshi,fenzhong,miao]];
   
}

@end

相關文章
相關標籤/搜索