扩展NSDate类实现快捷使用 —— 昉
获取当前日期和时间:
+(NSDate *)getCurrentDate{ NSDate *now = [NSDate date]; return now; }
将日期转换为字符串:
+(NSString *)getDateStringFromDate:(NSDate *)date{ NSInteger location = 0; NSString *timeStr = @""; NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; [formatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]]; [formatter setDateFormat:@"HH:mm:a"]; NSString *ampm = [[[formatter stringFromDate:date] componentsSeparatedByString:@":"] objectAtIndex:2]; timeStr = [formatter stringFromDate:date]; NSRange range = [timeStr rangeOfString:[NSString stringWithFormat:@":%@",ampm]]; location = range.location; NSString *string = [timeStr substringToIndex:location]; timeStr = [NSString stringWithFormat:@"%@ %@",ampm,string]; NSString *dateStr = @""; NSDateFormatter *Dformatter = [[[NSDateFormatter alloc] init] autorelease]; [Dformatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]]; [Dformatter setDateFormat:@"yyyy-MM-dd"]; dateStr = [Dformatter stringFromDate:date]; return [NSString stringWithFormat:@"%@ %@",dateStr,timeStr]; }
将字符串转换为日期:
+ (NSDate * )NSStringToNSDate: (NSString * )string { NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"]; NSDate *date = [formatter dateFromString :string]; return date; }
计算两个日期之间相差多少天:
+(NSInteger)getDateToDateDays:(NSDate *)date withSaveDate:(NSDate *)saveDate{
NSCalendar* chineseClendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar ];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit |
NSSecondCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
NSDateComponents *cps = [ chineseClendar components:unitFlags fromDate:date toDate:saveDate options:0];
NSInteger diffDay = [ cps day ];
return diffDay;
}
作者:SIBU iOS DEV
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.