ios 时间的比较&&获得系统本地时间指定时区

本文介绍了在iOS中如何比较两个日期以及获取系统本地时间并指定时区的方法,包括isEqualToDate:方法、earlierDate:、laterDate:、compare:方法的使用,以及如何设置NSDateFormatter获取'Asia/Beijing'时区的时间,同时提供了将字符串转换为日期及计算两个日期之间相差天数的方法。

ios 时间的比较&&获得系统本地时间指定时区

- (BOOL)isEqualToDate:(NSDate *)otherDate; 

 与otherDate比较,相同返回YES 

 - (NSDate *)earlierDate:(NSDate *)anotherDate;

 与anotherDate比较,返回较早的那个日期 

 - (NSDate *)laterDate:(NSDate *)anotherDate; 

 与anotherDate比较,返回较晚的那个日期

 - (NSComparisonResult)compare:(NSDate *)other;


 该方法用于排序时调用: .

  当实例保存的日期值与anotherDate相同时返回NSOrderedSame 

  . 当实例保存的日期值晚于anotherDate时返回NSOrderedDescending .

当实例保存的日期值早于anotherDate时返回NSOrderedAscending 

// 获得本地时间指定时区 NSDate *dates = [NSDate date]; 

  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

  [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 

  NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/beijing"];

  [formatter setTimeZone:timeZone]; 

  NSString *loctime = [formatter stringFromDate:dates];


-(NSDate *) stringToDate:string

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

  [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 

  NSDate *date = [dateFormatter dateFromString:string];

  [dateFormatter release]; return date;

}


-(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate

  NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

  unsigned int unitFlags = NSDayCalendarUnit; 

  NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0]; 

int days = [comps day]; return days;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值