首页 > 代码库 > 日期转换
日期转换
1、NSString日期转换成某种格式下的NSDate
+(NSDateFormatter*)chineseDateFormatter
{
NSDateFormatter *dataformatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
[dataformatter setLocale:locale];
[dataformatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:28800]];
return dataformatter;
}
+(NSDate*)date:(NSString*)date withFormat:(NSString*)formator
{
NSDateFormatter *formatter = [self chineseDateFormatter];
[formatter setDateFormat:formator];
NSDate *currentDate = [formatter dateFromString:date];
return currentDate;
}
或者:
+ (NSDate*)convertToDateFrom:(NSString*)dateText
withFomart:(NSString*)formatStyle {
NSDateFormatter *formater = [NSDateFormatter new];
[formater setLocale:[NSLocale currentLocale]];
[formater setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:28800]];
[formater setDateFormat:formatStyle];
NSDate *result = [formater dateFromString:dateText];
SafeRelease(formater);
return result;
}
2、NSDate类型的日期转换成某种格式下的NSString
+ (NSString*)convertToDateTextFrom:(NSDate*)date
withFomart:(NSString*)formatStyle {
NSDateFormatter *formater = [TRIPDateUtility tripDateFormatter];
[formater setDateFormat:formatStyle];
NSString *result = [formater stringFromDate:date];
SafeRelease(formater);
return result;
}
3、两个NSDate日期间隔计算
+ (NSDateComponents*)calculateDateDistanceFrom:(NSDate*)from
to:(NSDate*)to {
if (from == nil || to == nil) {
return nil;
}
NSCalendar *calender = [NSCalendar currentCalendar];
NSDateComponents *compoents = [calender components:NSCalendarUnitYear|NSCalendarUnitMonth|
NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute
fromDate:from
toDate:to
options:NSCalendarWrapComponents];
return compoents;
}
+ (NSTimeInterval)calculateTimeintervalFrom:(NSDate*)from
to:(NSDate*)to {
NSDate *beginningOfFrom = [from cc_dateByMovingToBeginningOfDay];
NSDate *beginningOfTo = [to cc_dateByMovingToBeginningOfDay];
return [beginningOfTo timeIntervalSinceDate:beginningOfFrom];
}
+ (NSTimeInterval)calculateDayCountFrom:(NSDate*)from
to:(NSDate*)to {
NSDate *beginningOfFrom = [from cc_dateByMovingToBeginningOfDay];
NSDate *beginningOfTo = [to cc_dateByMovingToBeginningOfDay];
return [beginningOfTo timeIntervalSinceDate:beginningOfFrom]/ 3600.0 / 24.0;
}
日期转换