当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

OC中关于日期与时间的处理

作者:小梦 来源: 网络 时间: 2024-08-24 阅读:

在我们的开发中与日期打交道是常有的事情,OC中提供了NSDate和NSCalendar来给我们进行时间相关的处理与操作,还是非常容易的,下面我们就一起看一看.

1.NSDate基本概念

NSDate可以用来表示时间, 可以进行一些常见的日期\时间处理,一个NSDate对象就代表一个时间

  • 获取系统当前时间
    NSDate *now = [NSDate date];

  • 获取系统当前时间戳
    NSTimeInterval nowTimestamp = [[NSDate date] timeIntervalSince1970] * 1000.0;

  • 计算时间间隔
    NSDate *myDate = [now timeIntervalSinceDate:otherDate];

    NSDate *now = [NSDate date];    NSLog(@"now = %@", now);     // 设置转换后的目标日期时区     NSTimeZone *zone = [NSTimeZone systemTimeZone];     // 得到源日期与世界标准时间的偏移量     NSInteger interval = [zone secondsFromGMTForDate: date];     NSLog(@"interval = %lu", interval);     // 在当前时间基础上追加时区差值     now = [now dateByAddingTimeInterval:interval];     NSLog(@"%@", date);

2.格式化日期

  • NSDate -> NSString

    // 1.创建时间    NSDate *now = [NSDate date];    // 2.创建时间格式化    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    // 3.指定格式    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";    // 4.格式化时间    NSString *str = [formatter stringFromDate:now];    NSLog(@"%@", str);
  • NSString -> NSDate

    NSString *str = @"2015-06-28 19:53:24";    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";    NSDate *date = [formatter dateFromString:str];    NSLog(@"%@", date);
  • 解析 欧美格式 日期字符串

- (void)fmt_string_to_date2{    // 服务器返回的时间字符串    NSString *string = @"Tue May 31 17:46:55 +0800 2011";    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    formatter.dateFormat = @"EEE MMM dd HH:mm:ss ZZZZ yyyy";       NSDate *date = [formatter stringFromDate:string];    NSLog(@"%@", date);}
  • timestamp -> NSDate

// 解析 时间戳- (void)fmt_string_to_date3{    // 时间戳: 从1970年1月1日开始经历的毫秒数    NSInteger timestamp = 1445164401875.157959;    // 获取系统当前的时间戳//    NSTimeInterval nowTimestamp = [[NSDate date] timeIntervalSince1970] * 1000.0;    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp/1000.0];    NSLog(@"%@", date);}

3.日期时间对象

结合NSCalendar和NSDate能做更多的 日期\时间 处理

  • 获得NSCalendar对象
    NSCalendar *calendar = [NSCalendar currentCalendar];

  • 获得年月日
    - (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)date;

    NSDate *date = [NSDate date];    // 1.创建日历对象    NSCalendar *calendar = [NSCalendar currentCalendar];    // 2.利用日历对象获取年月日时分秒    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;    NSDateComponents *components =[calendar components:type fromDate:date];    ?    NSLog(@"year = %lu", cmps.year);    NSLog(@"month = %lu", cmps.month);    NSLog(@"day = %lu", cmps.day);    NSLog(@"hour = %lu", cmps.hour);    NSLog(@"minute = %lu", cmps.minute);    NSLog(@"second = %lu", cmps.second);    NSLog(@"date = %@", date);
  • 比较两个日期的差距
    - (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSCalendarOptions)opts;

    // 1.确定时间    NSString *time1 = @"2015-06-23 12:18:15";    NSString *time2 = @"2015-06-28 10:10:10";    // 2.将时间转换为date    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";    NSDate *date1 = [formatter dateFromString:time1];    NSDate *date2 = [formatter dateFromString:time2];    // 3.创建日历    NSCalendar *calendar = [NSCalendar currentCalendar];     NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;    // 4.利用日历对象比较两个时间的差值    NSDateComponents *cmps = [calendar components:unit fromDate:date1 toDate:date2 options:0];    // 5.输出结果    NSLog(@"两个时间相差%ld年%ld月%ld日%ld小时%ld分钟%ld秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);

iOS8.0开始,NSCalendar增加了一些更为简单的判断日期的方法,如:

- (BOOL)isDate:(NSDate *)date1 equalToDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit;- (BOOL)isDate:(NSDate *)date1 inSameDayAsDate:(NSDate *)date2;- (BOOL)isDateInToday:(NSDate *)date;- (BOOL)isDateInYesterday:(NSDate *)date;- (BOOL)isDateInTomorrow:(NSDate *)date;- (BOOL)isDateInWeekend:(NSDate *)date;

但是iOS8.0以前是没有这些方法的,为了更好的兼容iOS8.0以前的项目,我们可以人为的给NSDate类做一些扩展.(新建继承自NSDate的分类,在分类里扩展方法)
代码如下所示:

#import "NSDate+BSExtension.h"@implementation NSDate (BSExtension)/** *  是否是今天 */- (BOOL)isToday{    NSCalendar *calendar = [NSCalendar currentCalendar];        NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;    // 获取时间    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];        return selfCmps.year == nowCmps.year && selfCmps.month == nowCmps.month && selfCmps.day == nowCmps.day;}/** *  是否是昨天 */- (BOOL)isYesterday{    // 生成只有年月日的日期对象    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];    fmt.dateFormat = @"yyyy-MM-dd";        NSString *selfString = [fmt stringFromDate:self];    NSDate *selfDate = [fmt dateFromString:selfString];        NSString *nowString = [fmt stringFromDate:[NSDate date]];    NSDate *nowDate = [fmt dateFromString:nowString];        // 比较时间差    NSCalendar *calendar = [NSCalendar currentCalendar];    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;    NSDateComponents *cmps = [calendar components:unit fromDate:selfDate toDate:nowDate options:0];        return cmps.year == 0 && cmps.month == 0 && cmps.day == 1;}/** *  是否是明天 */- (BOOL)isTomorrow{    // 生成只有年月日的日期对象    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];    fmt.dateFormat = @"yyyy-MM-dd";        NSString *selfString = [fmt stringFromDate:self];    NSDate *selfDate = [fmt dateFromString:selfString];        NSString *nowString = [fmt stringFromDate:[NSDate date]];    NSDate *nowDate = [fmt dateFromString:nowString];        // 比较时间差    NSCalendar *calendar = [NSCalendar currentCalendar];    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;    NSDateComponents *cmps = [calendar components:unit fromDate:selfDate toDate:nowDate options:0];        return cmps.year == 0 && cmps.month == 0 && cmps.day == -1;}/** *  是否是今年 */- (BOOL)isThisYear{    NSCalendar *calendar = [NSCalendar currentCalendar];        NSInteger selfYear = [calendar component:NSCalendarUnitYear fromDate:self];    NSInteger nowYear = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];        return selfYear == nowYear;}@end

热点阅读

网友最爱