// NSDateFormatter是用来设置NSDate的格式 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; // 设置为系统时区 formatter.timeZone = [NSTimeZone systemTimeZone]; // 用来设置NSDate的输出格式 formatter.dateFormat = @" yyyy-MM-dd HH:mm:ss " ; // 用来讲本地时间转换成字符串的形式输出 NSString *timeStr = [formatter stringFromDate:[NSDate date]]; NSLog( @" 本地时间 NSDate的输出格式 %@ " ,timeStr);

除此之外,日期之间比较可用以下方法:

    //与otherDate比较,相同返回YES
    - (BOOL)isEqualToDate:(NSDate *)otherDate;
    //与anotherDate比较,返回较早的那个日期
    - (NSDate *)earlierDate:(NSDate *)anotherDate;
    //与anotherDate比较,返回较晚的那个日期
    - (NSDate *)laterDate:(NSDate *)anotherDate;

二、NSDateFormatter

    //将字符串转换为日期对象.
    NSString *dateStrs = @"2020-01-01-18:10:00";
    NSDateFormatter *formatterTime = [NSDateFormatter new];
    formatterTime.dateFormat = @"yyyy-MM-dd-HH:mm:ss";
    formatterTime.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSDate *dateTime = [formatterTime dateFromString:dateStrs];
    NSLog(@"将字符串转换为日期对象date %@",dateTime);

将时间字符串转换到NSDate对象,一般都是使用"年月日 时分秒",数据库中的date类型基本上也是这样的时间类型。 格式一般为:yyyy-MM-dd HH:mm:ss。

注意:yyyy是小写的;大写的YYYY的意思有些不同——“将这一年中第一周的周日当作今年的第一天”,因此有时结果和yyyy相同,有时就会不同。

将NSDate对象转换成特定格式的字符串。

转换后的字符串会根据设备的“区域格式”,显示特定语言的结果。假如程序需要保证不同语言环境下显示一致,请注意这方面的问题,使用其他代替方法!

    // NSDate 转换成时间戳
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]];
    NSLog(@"timeSp : %@", timeSp);
    // 时间戳转换成NSDate
    NSDate *currentTime = [NSDate dateWithTimeIntervalSince1970:[timeSp intValue]];
    NSLog(@"currentTime : %@", currentTime);

四、NSCalendar

  • NSCalendar对世界上现存的常用的历法进行了封装,既提供了不同历法的时间信息,又支持日历的计算。
  • NSDateComponents将时间表示成适合人类阅读和使用的方式,通过NSDateComponents可以快速而简单地获取某个时间点对应的“年”,“月”,“日”,“时”,“分”,“秒”,“周”等信息。当然一旦涉及了年月日时分秒就要和某个历法绑定,因此NSDateComponents必须和NSCalendar一起使用,默认为公历。
  • NSDateComponents返回的day, week, weekday, month, year这一类数据都是从1开始的。因为日历是给人看的,不是给计算机看的,从0开始就是个错误。
  •     //取到NSDate对象的各个部分  年 月 日 周
        //1. 创建1个当前的日历对象.
        //   作用: 可以取到1个日期对象的各个部分.
        NSCalendar *calendar = [NSCalendar currentCalendar];
        //2. 指定日历对象,要去取日期对象的那些部分.
        NSDateComponents *comp =  [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:date];
        //3. 通过NSDateComponents取到指定的日期的各个部分.
        NSLog(@"%lu",comp.year);
        NSLog(@"%lu",comp.month);
        NSLog(@"%lu",comp.day);
        NSLog(@"%lu",comp.weekday);