有时候开发中我们只需要年月日、或者只需要时分秒,刚开始由于对NSDate不是很熟悉,走了很多弯路,特在此记录!!回头要好好把NSDate的文档好好看看
NSDate *date = _datePickerView.date; NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; // Get Current Hour [formatter setTimeStyle:NSDateFormatterShortStyle]; NSLog(@"test------ %@",[formatter stringFromDate:date]); <pre name="code" class="objc">//这样设置得到的格式是这样的: test------ 下午2:19
[formatter setDateStyle:NSDateFormatterShortStyle]; NSLog(@"test+_+++++++ %@",[formatter stringFromDate:date]);
//test+_+++++++ 14-8-12 下午2:19
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
NSLog(@"test+_+++++++ %@",[formatter stringFromDate:date]);
//test+_+++++++ 14-8-12
由上面可以知道,我们可以通过设置 setDateStyle 和setTimeStyle的格式来分别得到我们想要的结果:日期、时间等
如果我们想获取年、或者月、或者日、或者小时、或者分钟等单个值时该如何做呢?看代码如下:
NSDate *date = [NSDate date]; // Get Current Year NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; [formatter setDateFormat:@"yyyy"]; NSString *currentyearString = [NSString stringWithFormat:@"%@", [formatter stringFromDate:date]]; // Get Current Month [formatter setDateFormat:@"MM"]; currentMonthString = [NSString stringWithFormat:@"%d",[[formatter stringFromDate:date]integerValue]]; // Get Current Date [formatter setDateFormat:@"dd"]; NSString *currentDateString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]]; // Get Current Hour [formatter setDateFormat:@"hh"]; NSString *currentHourString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]]; // Get Current Minutes [formatter setDateFormat:@"mm"]; NSString *currentMinutesString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]]; // Get Current AM PM [formatter setDateFormat:@"a"]; NSString *currentTimeAMPMString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
开发中关于日期的处理:NSDate中取出日期、取出时间等
时间: 2024-12-22 06:03:32