iOS基础知识:Objective-C 之 NSDate,NSCalendar,NSTimer

定时器与日历


NSDate

得到现在的date

    //get current date at +0000
    NSDate *date = [NSDate date];
    NSLog(@"date:%@",date);

以字符串形式表示date

    //get description with current locale
    NSString *dateStr = [date descriptionWithLocale:[NSLocale currentLocale]];
    NSLog(@"dateStr:%@",dateStr);

比较两个date,哪个时间早,哪个时间晚,算出时间差

    //get earlier/later date ,get time minus
    NSDate *date1 = [NSDate dateWithTimeIntervalSinceNow:100];
    NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow:-100];
    NSDate *earlierDate = [date1 earlierDate:date2];
    NSDate *laterDate = [date1 laterDate:date2];
    NSUInteger timeSec = [date1 timeIntervalSinceDate:date2];
NSLog(@"\nearlierDate:%@\nlaterDate:%@\ntimeInterval:%lu",earlierDate,laterDate,timeSec);

将date转化成指定格式的字符串

    //dateFormat
    //string from date
    NSDateFormatter *dateFormat = [NSDateFormatter new];
    dateFormat.dateFormat = @"YYYY年MM月dd日 HH时mm分ss秒 EEEE";
    NSString *formatStr = [dateFormat stringFromDate:date];
    NSLog(@"formatStr:%@",formatStr);

将指定格式的字符串转化成date

    //date from string
    dateFormat.dateFormat = @"YYYY-MM-dd HH-mm-ss";
    formatStr = @"2015-6-3 13-00-00";
    NSDate *formatDate = [dateFormat dateFromString:formatStr];
    NSLog(@"formatDate:%@",formatDate);

NSCalendar
从一个date中得到年、月、日、时、分、秒、星期等元素

    //get date component from calendar
    NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *dateComponent = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];

    NSLog(@"%lu year %lu month %lu day",dateComponent.year,dateComponent.month,dateComponent.day);

得到某个月有多少天

    //how many days in date's month
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
    NSLog(@"range:(%lu,%lu)",range.location,range.length);

得到date是在当前年的第几周

    //number weekdays in year
    NSUInteger ordinal = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:[NSDate date]];
    NSLog(@"ordinal:%lu",ordinal);

从年、月、日、时、分、秒等元素,来创建一个date

    //creat date from date components
    NSDateComponents *comp = [NSDateComponents new];
    comp.year = 2015;
    comp.month = 6;
    comp.day = 3;
    NSDate *compDate = [calendar dateFromComponents:comp];
    NSLog(@"compDate:%@",[compDate descriptionWithLocale:[NSLocale currentLocale]]);

基于一个date,来创建另外一个date;

    //creat a date later date components
    NSDateComponents *comp1 = [NSDateComponents new];
    comp1.hour = 5;
    NSDate *newDate = [calendar dateByAddingComponents:comp1 toDate:[NSDate date] options:0];
    NSLog(@"newDate:%@",[newDate descriptionWithLocale:[NSLocale currentLocale]]);

计算从某一时刻起,到指定的date,有多少年、月、日等元素

    //calculate how many months from 1970
    NSDateComponents *comp2 = [calendar components:NSCalendarUnitMonth fromDate:[NSDate dateWithTimeIntervalSince1970:0] toDate:[NSDate date] options:0];
    NSLog(@"%lu",comp2.month);

NSTimer
1、creat a timer and count since now

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(didTimerFired:) userInfo:nil repeats:YES];

上面就创建了一个timer,并且每间隔1.0秒就会自动调用一次[self didTimerFired:timer];

2、creat a timer and count after date that you specifid

//与上一段代码相比,类方法名少了个scheduled
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(didTimerFired:) userInfo:nil repeats:YES];
    //此处为手动触发一次Fire
    [timer fire];
    //设置fireDate,默认为当前date
    [timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:10]];
    //监控timer,如果没有下面这条语句,timer将不会调用fire
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

3、NSTimer 的精度只能达到50ms-100ms,相对较低,如果想要精度高的定时,可以用GCD

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是用Objective-C纯代码实现的签到日期界面。实现的界面包括一个导航栏、一个显示当前日期的标签和一个签到按钮。 ViewController.h文件: ```objective-c #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end ``` ViewController.m文件: ```objective-c #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UILabel *dateLabel; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. // 设置导航栏标题 self.navigationItem.title = @"签到"; // 设置背景颜色 self.view.backgroundColor = [UIColor whiteColor]; // 创建并添加日期标签 self.dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)]; self.dateLabel.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 - 50); self.dateLabel.textAlignment = NSTextAlignmentCenter; self.dateLabel.textColor = [UIColor blackColor]; [self.view addSubview:self.dateLabel]; // 更新日期标签的文本 [self updateDateLabel]; // 创建并添加签到按钮 UIButton *checkInButton = [UIButton buttonWithType:UIButtonTypeSystem]; checkInButton.frame = CGRectMake(0, 0, 200, 50); checkInButton.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 + 50); [checkInButton setTitle:@"签到" forState:UIControlStateNormal]; [checkInButton addTarget:self action:@selector(checkInButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:checkInButton]; } // 更新日期标签的文本 - (void)updateDateLabel { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyy年MM月dd日"; self.dateLabel.text = [formatter stringFromDate:[NSDate date]]; } // 签到按钮点击事件 - (void)checkInButtonClicked:(UIButton *)sender { // TODO: 处理签到逻辑 // 更新日期标签的文本 [self updateDateLabel]; } @end ``` 在AppDelegate.m文件中,将ViewController设置为根视图控制器: ```objective-c #import "AppDelegate.h" #import "ViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; ViewController *viewController = [[ViewController alloc] init]; UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; self.window.rootViewController = navigationController; [self.window makeKeyAndVisible]; return YES; } ``` 这样就完成了一个简单的签到日期界面的实现。运行程序后,可以看到一个带有日期标签和签到按钮的界面。点击签到按钮后,日期标签上的日期会更新为当前日期。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值