自定义了一个日期选择器,与大家分享一下,期待宝贵建议。github下载地址:https://github.com/huahua0809/XHDatePicker
代码片段下载地址
https://git.oschina.net/qjz.com/NSDate_Tool/tree/master
需求说明:获取服务器返回的时间,与当前时间对比,计算出时间差,并根据时间差的长短显示不同的形式。
工具类使用例子:
//时间属性的get方法
-(NSString \*)create_time
{
// 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
// 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒)
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// 帖子的创建时间
NSDate *create=[fmt dateFromString:_create_time];
if (create.isThisYear) {//如果是今年
NSDateComponents *cmps=[[NSDate date] deltaFrom:create];
if (cmps.hour>=1) {//如果大于一个小时
return [NSString stringWithFormat:@"%zd小时前",cmps.hour];
}else if (cmps.minute>=1)//如果大于一分钟
{
return [NSString stringWithFormat:@"%zd分钟前",cmps.minute];
}else
{
return @"刚刚";
}
}else
{
return _create_time;
}
}
NSDate相关的一些操作
-----日期转字符串
// 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
// 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒)
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// 帖子的创建时间
NSDate *create=[fmt dateFromString:_create_time];
-----字符串转日期
//需要转换的字符串
NSString *dateString = @"2015-06-26 08:08:08";
//设置转换格式
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//NSString转NSDate
NSDate *date=[formatter dateFromString:dateString];
----获取现在的时间是几月几日星期几
NSDate* now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit;
NSDateComponents *dd = [cal components:unitFlags fromDate:now];
int m = [dd month];
int d = [dd day];
NSString *dataStr = [NSString stringWithFormat:@"%d月%d日 ",m,d];
//日期转换成周几
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"eeee"];
NSString *newDateString = [outputFormatter stringFromDate:now];
NSString *dayStr;
if ([newDateString isEqualToString:@"Monday"]||[newDateString isEqualToString:@"星期一"])
dayStr = @"星期一";
else if ([newDateString isEqualToString:@"Tuesday"]||[newDateString isEqualToString:@"星期二"])
dayStr = @"星期二";
else if ([newDateString isEqualToString:@"Wednesday"]||[newDateString isEqualToString:@"星期三"])
dayStr = @"星期三";
else if ([newDateString isEqualToString:@"Thursday"]||[newDateString isEqualToString:@"星期四"])
dayStr = @"星期四";
else if ([newDateString isEqualToString:@"Friday"]||[newDateString isEqualToString:@"星期五"])
dayStr = @"星期五";
else if ([newDateString isEqualToString:@"Saturday"]||[newDateString isEqualToString:@"星期六"])
dayStr = @"星期六";
else if ([newDateString isEqualToString:@"Sunday"]||[newDateString isEqualToString:@"星期日"])
dayStr = @"星期日";