获取当前时间和之前存储的时间作比较

@property (strong, nonatomic)NSUserDefaults * date;
- (IBAction)LoginAction:(id)sender;

@end

@implementation ViewController
{
NSTimeInterval time1;
}
- (void)viewDidLoad {
[super viewDidLoad];
}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

  • (IBAction)LoginAction:(id)sender {

    // 修改默认时区会影响时间的输出显示
    [NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithAbbreviation:@”GMT+0900”]];
    // 只能够修改该程序的defaultTimeZone,不能修改系统的,更不能修改其他程序的。
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@”yyyy-MM-dd HH:mm:ss”];

    NSDate *now = [NSDate date];

    time1 = [now timeIntervalSince1970];

    NSLog( @”time1 == %d”,(int)time1);
    NSNumber * number1 = [NSNumber numberWithDouble:time1];

    if ([self.date objectForKey:@”1”] == nil) {
    [_date setObject:number1 forKey:@”1”];
    }
    [_date synchronize];

    NSInteger num = [self getDaysFrom:[NSDate dateWithTimeIntervalSince1970:[[_date objectForKey:@”1”] integerValue]] To:[NSDate dateWithTimeIntervalSince1970:(NSInteger)time1]];
    NSLog(@”— %ld”, num);
    }

  • (NSInteger)getDaysFrom:(NSDate )serverDate To:(NSDate )endDate
    {
    NSCalendar *gregorian = [[NSCalendar alloc]
    initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    [gregorian setFirstWeekday:2];

    //去掉时分秒信息
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:serverDate];
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:endDate];
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];

    return dayComponents.day;
    }

  • (NSUserDefaults *)date{
    if (!_date) {
    _date = [NSUserDefaults standardUserDefaults];
    }return _date;
    }

你可能感兴趣的:(iOS)