灵心如玉,守一生无惧|

SadicZhou

园龄:3年2个月粉丝:7关注:4

IOS开发-与时间相关NSCalendar、NSDate类的基本使用

1.获取世界统一时间和当前城市时间

-(void)getNowDate{
    NSDate *nowDate = [NSDate date];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    NSInteger ti = [localTimeZone secondsFromGMTForDate:nowDate];
    NSDate *newDate = [nowDate dateByAddingTimeInterval:ti];
    NSLog(@"世界统一时间:%@ 当地时间:%@", nowDate, newDate);

}

 2.获取当前时间的时分秒

复制代码
-(void)getFormattdate{
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

    NSDateComponents *components = [calendar components:unit fromDate:[NSDate date]];

    NSLog(@"年:%ld 月:%ld 日:%ld 时:%ld 分:%ld 秒:%ld",(long)components.year, (long)components.month, (long)components.day, (long)components.hour, (long)components.minute, (long)components.second);
}
复制代码

3.比较两个时间之间的差值

复制代码
-(void)compareDate{
    NSDate *date1 = [NSDate date]; // 当前的日期

    NSString *dateStr = @"2015-06-29 07:05:26 +0000";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
    NSDate *date2 = [formatter dateFromString:dateStr];  // 指定的日期

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *components = [calendar components:unit fromDate:date1 toDate:date2 options:0];

    NSLog(@"相差年:%ld 月:%ld 日:%ld 时:%ld 分:%ld 秒:%ld",(long)components.year, (long)components.month, (long)components.day, (long)components.hour, (long)components.minute, (long)components.second);
}
复制代码

4.获取当前日期的那天在所在月份是星期几 

复制代码
-(void)getWeek{
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = 2016;
    components.month = 1;
    components.day = 4;
        
    NSDate *date = [calendar dateFromComponents:components];

    NSUInteger index = [calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekOfMonth forDate:[NSDate date]];
    NSLog(@"--%lu", index);
    //1:代表星期日  2:代表星期一  3:代表星期二  4:代表星期三  5:代表星期四  6:代表星期五  7:代表星期六
}
复制代码

 

本文作者:ZihangChu

本文链接:https://www.cnblogs.com/SadicZhou/p/17565238.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   SadicZhou  阅读(166)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 尚好的青春 孙燕姿
  2. 2 孙燕姿
  3. 3 克卜勒 孙燕姿
- 孙燕姿
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.