IOS 公共类-MyDateUtil 日期处理Util
此为处理日期的公共类。适用IOS6+
.h文件:
#import <Foundation/Foundation.h>
//适用 IOS6+
@interface MyDateUtil //返回一个新的日期,新的日期将会只保留年月日
+(NSDate*) keepYearMonthDayWithDate:(NSDate*)oldDate;
//返回日期的年份
+(int)getYearWithDate:(NSDate *)date;
//返回日期的月份
+(int) getMonthWithDate:(NSDate*) date;
//返回日期的日份
+(int) getDayWithDate:(NSDate*) date;
//传入年月日,返回日期类型
+(NSDate*) getDateFromYear:(int)year andMonth:(int)month andDay:(int)day;
//传入一个日期的字符串,一个日期字符串的分隔符,返回日期。 默认为"/",即传入"01/05/2012"和"/",返回日期类型。 "dd/MM/yyyy" "01/05/2012"
+(NSDate*) getDateFromText:(NSString*)dateStr andDateSplit:(NSString*)split;
.m文件:
#import <Foundation/Foundation.h> @implementation MyDateUtil:NSObject +(NSDate*) keepYearMonthDayWithDate:(NSDate*)oldDate {
NSCalendar *oldCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *oldDateComponents = [oldCal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:oldDate]; NSDate *result = [oldCal dateFromComponents:oldDateComponents];
return result;
} +(int)getYearWithDate:(NSDate *)date {
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
return dateComp.year;
} +(int) getMonthWithDate:(NSDate*) date {
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
return dateComp.month;
} +(int) getDayWithDate:(NSDate*) date {
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
return dateComp.day;
} +(NSDate*) getDateFromYear:(int)year andMonth:(int)month andDay:(int)day {
NSDateComponents *dateComp = [[NSDateComponents alloc] init];
dateComp.year = year;
dateComp.month = month;
dateComp.day = day;
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *d = [cal dateFromComponents:dateComp];
return d;
} //datestr must like: "dd/MM/yyyy" "01/05/2012"
+(NSDate*) getDateFromText:(NSString*)dateStr andDateSplit:(NSString*)split{
if (!split) {
split = @"/";
}
NSArray *dateStrArr = [dateStr componentsSeparatedByString:@"/"];
return [self getDateFromYear:[[dateStrArr objectAtIndex:] intValue] andMonth:[[dateStrArr objectAtIndex:] intValue] andDay:[[dateStrArr objectAtIndex:] intValue]];
} @end
若要下载,请访问github:https://github.com/cjt321/MyDateUtil
此处保持最新更新