您的位置:首页 > 移动开发 > IOS开发

iOS NSDate的基本使用,获取时间戳

2016-05-26 15:10 597 查看
// 这里进行一次分析

1.首先根据传进来的formatString做一个格式对象出来,nil的话就默认为yyyy-MM-dd
HH:mm:ss

2.NSTimerInterval timeInterval = [当前时间 timeIntervalSinceDate:发布时间];

3.当前时间获取

NSDate *当前时间 = [NSDate date] //!<这里获取的是当前时间对象,格林尼治的

NSString *当前时间字符串 = [格式对象 stringFromDate:] //!<先转换成字符串进行一次中间变换

NSDate *最终的当前时间对象 = [格式对象 dateFromString:当前时间字符串];//!<这个时候字符串就变成了当地时区的时间对象了,完美!!

4.获取传进来时间的对象 发布时间类似于微博发布的一个时间点 //!<根据指定的timeIntervale来获取对象

NSDate *发布时间 = [NSDate dateWithTimeIntervalSince1970:(这里把传入的字符串转换成浮点型)]

5.算出来之后就是一个NSTimeInterval,然后根据判断获取到具体的字符串返回

代码如下:

+(NSString *)internalFromCreatTime:(NSString *)creatTimeString formatString:(NSString *)formatString

{

//创建对应的格式

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];

[dateFormatter setDateFormat:formatString?formatString:@"yyyy-MM-dd HH:mm:ss"];

//生成对应的格式日期对象

NSDate *currentDate=[dateFormatter dateFromString:[dateFormatter stringFromDate:[NSDate new]]];

NSDate *nd = [NSDate dateWithTimeIntervalSince1970:creatTimeString.floatValue];

//计算日期间隔

NSTimeInterval timeInterval= [currentDate timeIntervalSinceDate:nd];

float days = timeInterval / (3600.0*24);

float hours=timeInterval /3600.0;

float minutes = timeInterval / 60;

if (days >7)

{

return [dateFormatter stringFromDate:nd];

}

else if (days>=1)

{

return [NSString stringWithFormat:@"%d天前",(int)days];

}

else if (hours>=1)

{

return [NSString stringWithFormat:@"%d小时前",(int)hours];

}

else

{

return [NSString stringWithFormat:@"%d分钟前",(int)minutes];

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: