iOS-关于日期

  • 指定的数字转NSDate
    NSDateComponents *comp = [[NSDateComponents alloc] init];
    comp.year = 2018;
    comp.month = 6;
    comp.day = 13;
    comp.hour = 17;
    comp.minute = 8;
    comp.second = 22;
    NSDate *dateFromStringDate = [[NSCalendar currentCalendar] dateFromComponents:comp];
    NSLog(@"dateFromStringDate = %lf", [dateFromStringDate timeIntervalSince1970]);
  • 时间字符串和NSDate互转。使用NSDateFormatter

方法:- (NSString *)stringFromDate:(NSDate *)date;// NSDate转字符串

NSDateFormatter *formt = [[NSDateFormatter alloc] init];
    formt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *stringDate = [formt stringFromDate:[NSDate date]];
    NSLog(@"stringDate = %@", stringDate);

方法:- (nullable NSDate *)dateFromString:(NSString *)string;// 时间字符串转NSDate

    NSDateFormatter *formt = [[NSDateFormatter alloc] init];
    formt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *dateFromStringDate = [formt dateFromString:@"2018-6-13 17:18:30"];
    NSLog(@"dateFromStringDate = %lf", [dateFromStringDate timeIntervalSince1970]);

你可能感兴趣的:(iOS-关于日期)