NSDate-常用操作及控制
对于NSDate常用操作整理,如有不足请补充
1,获取当前时区时间
//初始化时间段
NSDate *date = [nsdate date];
//获取当前时区
NSTimeZone *zone = [nstimezone systemtimezone];
//以秒为单位返回当前应用程序与世界标准时间(格林威尼时间)的时差
NSInteger interval = [zone secondsfromgmtfordate: date];
//补充时差后为当前时间
NSDate *localeDate = [date datebyaddingtimeinterval: interval];
2,将字符串格式化NSDate
NSString *dateStr=@"2013-08-13 20:28:40";
//格式化
NSDateFormatter *dateFormatter = [[nsdateformatter alloc] init];
[dateformatter setdateformat:@"yyyy-mm-dd hh:mm:ss"];
NSDate *fromdate=[dateformatter datefromstring:datestr];
//时区
NSTimeZone *fromzone = [nstimezone systemtimezone];
//同例1
NSInteger frominterval = [fromzone secondsfromgmtfordate: fromdate];
NSDate *fromDate = [fromdate datebyaddingtimeinterval: frominterval];
NSLog(@"fromdate=%@",fromDate);
//将NSDate转为NSString
NSString *strTime = [fromdate description];
//如果直接将NSDate格式化
NSDate *recv = [nsdate datefromstring:recvtime withformat:@"yyyy-mm-dd hh:mm:ss z"];
3,比较两个时间相差(年月日,时分秒)
double intervalTime = [fromdate timeintervalsincereferencedate] - [localedate timeintervalsincereferencedate];
long lTime = (long)intervalTime;
NSInteger iSeconds = lTime % 60;
NSInteger iMinutes = (lTime / 60) % 60;
NSInteger iHours = (lTime / 3600)$;
NSInteger iDays = lTime/60/60/24;
NSInteger iMonth = lTime/60/60/24/12;
NSInteger iYears = lTime/60/60/24/384;
NSLog(@"相差M年d月 或者 d日d时d分d秒", iYears,iMonth,iDays,iHours,iMinutes,iSeconds);
4,按日期排序
//与otherDate比较,相同返回YES
- (BOOL)isEqualToDate:(NSDate *)otherDate;
//与anotherDate比较,返回较早的那个日期
- (NSDate *)earlierDate:(NSDate *)anotherDate;
//与anotherDate比较,返回较晚的那个日期
- (NSDate *)laterDate:(NSDate *)anotherDate;
//该方法用于排序时调用
- (NSComparisonResult)compare:(NSDate *)other;
//. 当实例保存的日期值与anotherDate相同时返回NSOrderedSame
//. 当实例保存的日期值晚于anotherDate时返回NSOrderedDescending
//. 当实例保存的日期值早于anotherDate时返回NSOrderedAscending
5,从NSDate中获取年月日,时分秒
NSCalendar *calendar = [[nscalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *comps = [calendar components:unitflags fromdate:date];
int year = [comps year];
int month = [comps month];
int day = [comps day];
int hour = [comps hour];
int min = [comps minute];
int sec = [comps second];
//获取数据有异常 // NSError *error = init]; // NSData *pData = = ; // NSLog(@"download string end error = %d", ); // ;
判断12小时或24小时(制)
NSDateFormatter *dateFormatter = [[nsdateformatter alloc] init];
[dateformatter setdateformat:@"a"];
NSString *AMPMtext = [dateformatter stringfromdate:[nsdate date]];
[dateformatter release];
if ([ampmtext isequaltostring:@""]){
NSLog(@"24小时制");
}
else {
NSLog(@"12小时制");
}