NSDate + Change .h文件
#import <Foundation/Foundation.h> @interface NSData (Change) + (NSDate *)change; + (NSDate *)getDateWithDateString:(NSString *)strDate; @end
NSDate + Change .m文件
#import "NSData+Change.h" @implementation NSData (Change) + (NSDate *)change { NSString *str = @"20140402142850"; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"YYYYMMddHHmmss"]; // NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; //上面两行是设置时区加上八个小时 NSDate *dateTime =[formatter dateFromString: str]; return dateTime; } + (NSDate *)getDateWithDateString:(NSString *)strDate { // NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; // [formatter setDateFormat:@"YYYYMMddHHmmss"]; // NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; // [formatter setTimeZone:timeZone]; //上面两行是设置时区加上八个小时 // NSDate *dateTime =[formatter dateFromString: strDate]; // return dateTime; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"YYYYMMddHHmmss"]; NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; [formatter setTimeZone:timeZone]; NSDate *dateTime = [formatter dateFromString:strDate]; return dateTime; } @end
main.m中代码
NSDate *a =[NSData change]; NSLog(@"%@",a); NSDate *aa = [NSData getDateWithDateString:@"20140402142850"]; NSLog(@"%@",aa); /* 1.Category定义的方法优先级比本类中的方法高 2.Category只能定义方法,不能勋仔实例变量 3.Category定义的方法如果和本类中的法方重名,会出现警告。 */
//1.利用NSDateFormatter将日期按照一定格式输出:转换成字符串 /* NSDate *date = [NSDate date]; NSDateFormatter *fra = [[NSDateFormatter alloc] init]; [fra setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; NSString *dateStr = [fra stringFromDate:date]; NSLog(@"%@",dateStr); */ //2.将格式串对象按照NSDate对象输出 /* //创建字符串 NSString *dateStr = @"2008-08-08 20:08:08"; //创建格式化对象 NSDateFormatter *fra = [[NSDateFormatter alloc] init]; //设置输出格式 [fra setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //将格式穿对象转换成NSDate对象 NSDate *date1 = [fra dateFromString:dateStr]; NSLog(@"%@",date1); */
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。