1. 获取年月日时分秒
NSDate *date1 = [NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateStyle:NSDateFormatterMediumStyle];
[formatter1 setTimeStyle:NSDateFormatterShortStyle];
[formatter1 setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
NSString *DateTime1 = [formatter1 stringFromDate:date1];
str就是我们需要的时间,代码中("YYYY-MM-dd HH:mm:ss")这个时间的样式是可以根据我们的需求进行修改的,比如: 20170901112253 ==> ("YYYYMMddHHmmss")
如果只想获取年月,代码如下:
NSDate *date1 = [NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateStyle:NSDateFormatterMediumStyle];
[formatter1 setTimeStyle:NSDateFormatterShortStyle];
[formatter1 setDateFormat:@"YYYY-MM"];
NSString *DateTime1 = [formatter1 stringFromDate:date1];
2. 区分系统时间是24小时制还是12小时制
//获取系统是24小时制或者12小时制
NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
NSRange contains = [formatStringForHours rangeOfString:@"a"];
BOOL thisAMPM = contains.location != NSNotFound;
thisAMPM == true //表示12小时制 否则为24小时制
3. 字符串转时间戳
//字符串转时间戳
//datenow为当前时间
NSString *timeSp = [NSString stringWithFormat:@"%d", (long)[datenow timeIntervalSince1970]];
//时间戳的值
NSLog(@"timeSp:%@",timeSp);
4.时间戳转字符串
//时间戳转字符串
NSString *timeStr = "1506064573";
NSTimeInterval interval=[timeStr doubleValue] / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
//实例化一个NSDateFormatter对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//设定时间格式,这里可以设置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *currentDateStr = [dateFormatter stringFromDate:date];