你的位置:首页 > 操作系统

[操作系统]IOS阶段学习第15天笔记(OC关于NSDate的操作)


 1 NSDate *newdate=[NSDate date]; 2 //时间格式化字符串 3 NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; 4 [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss MMM eee a"]; 5 NSString *strdate = [formatter stringFromDate:newdate]; 6 NSLog(@"%@",strdate); 7  8 //时间字符串转换为时间类型 9 NSDateFormatter * formatter2 = [[NSDateFormatter alloc]init];10 NSString * nstr =@"2014年05月01日 10点23分18秒";11 [formatter2 setDateFormat:@"yyyy年MM月dd日 hh点mm分ss秒"];12 NSDate * date3 = [formatter2 dateFromString:nstr];13 //解决时分秒转换不准确问题14 NSTimeZone *fzone = [NSTimeZone systemTimeZone];15 NSInteger finterval = [fzone secondsFromGMTForDate: date3];16 NSDate *fDate = [date3 dateByAddingTimeInterval: finterval];17 NSLog(@"%@",fDate);18 19 //获取系统时间的年月日时分秒部分20 NSCalendar *cal = [NSCalendar currentCalendar];21 //Mac 10.10以前的系统使用 NSYearCalendarUnit22 unsigned int unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;23 NSDateComponents *d = [cal components:unitFlags fromDate:newdate];24 NSLog(@"年=%ld",[d year]);25 NSLog(@"月=%ld",[d month]);26 NSLog(@"日=%ld",[d day]);27 NSLog(@"时=%ld",[d hour]);28 NSLog(@"分=%ld",[d minute]);29 NSLog(@"秒=%ld",[d second]);30 31 //将传入时间字符串转换成需要的时间格式32 NSString *dateStr=@"2013-08-13 20:28:40";34 NSDateFormatter *format=[[NSDateFormatter alloc] init];35 [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];36 NSDate *fromdate=[format dateFromString:dateStr];37 //解决时分秒转换不准确问题38 NSTimeZone *fromzone = [NSTimeZone systemTimeZone];39 NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];40 NSDate *fromDate = [fromdate dateByAddingTimeInterval: frominterval];41 NSLog(@"fromdate=%@",fromDate);