Advertisement

通过日期计算距离当前时间的距离

阅读量:

格式1 通过(2014-12-11 22:22:22) 获得 今天22:22 ,昨天22:22 , 2天前 , 1个月前 , 3年前

NSString *dateStr = @"2015-01-15 22:22:22";

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

[dateFormat setDateFormat:@"yyyy-MM-dd"];

rangeBar r = dateStr.range(of: NSBackwardSearch); // 确定日期字符串中最后一个-出现的位置

让我们将Objective-C时间设置为从位置r.location加3处提取的时间字符串。

let timeInterval = (NSDate.date - date).timeIntervalSinceDate;
// 计算date与当前系统时间之间的总秒数

int year = ((int)time / (3600 * 24 * 30 * 12));

int month = ((int)time / (3600 * 24 * 30));

int day = ((int)time / (3600 * 24));

NSString *dateContent;

if (year != 0) {

dateContent = [NSString stringWithFormat:@"%i年前", year];

} else if (month != 0) {

dateContent = [NSString stringWithFormat:@"%i个月前", month];

} else {

r = [dateStr rangeOfString:@":"];

if (day == 0) {

currentDay = [NSString stringWithFormat:"current day", [currentDate substringWithRange:substring from position of r minus 2 for length 5]];

} else if (day == 1) {

dateContent = [NSString stringWithFormat:@"昨日@", [dateStr substringWithRangeOfStartIndex: r.location减去2个单位, length:5]];

} else {

dateContent = [NSString stringWithFormat:@"%i天前", day];

}

}

格式2 通过(2003-22-22 12:22:33) 获得 刚刚 , 20秒前 , 3分钟前 , 1小时前 , 2天前 , 1周前 , 5个月前 , 2年前

NSString *dateStr = @"2015-01-15 12:11:11";

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

[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *date = [dateFormat dateFromString:dateStr];

double deltaSeconds = fabs([[NSDate date] timeIntervalSinceDate: date]); // 获取全部秒数

double deltaMinutes = deltaSeconds / 60.0f;

NSString *dateContent;

if (deltaSeconds < 5) {

dateContent = @"刚刚";

} else if (deltaSeconds < 120) {

dateContent = @"1分钟前";

} else if (deltaMinutes < 60) {

dateContent = [NSString stringWithFormat:@"%i分钟前", (int)deltaMinutes];

} else if (deltaMinutes < 120) {

dateContent = @"1小时前";

} else if (deltaMinutes < (24 * 60)) {

日期内容 = [NSString stringWithFormat "%i小时前", (int) floor(deltaMinutes / 60)]

} else if (deltaMinutes < (24 * 60 * 2)) {

dateContent = @"昨天";

} else if (deltaMinutes < (24 * 60 * 7)) {

dateContent = [NSString stringWithFormat:@"%d天前", (int)floor(deltaMinutes/(60 * 24))];

} else if (deltaMinutes < (24 * 60 * 14)) {

dateContent = @"上周";

} else if (deltaMinutes < (24 * 60 * 31)) {

dateContent = [NSString stringWithFormat:@"%d周前", (int)floor(deltaMinutes/(60 * 24 * 7))];

} else if (deltaMinutes < (24 * 60 * 61)) {

dateContent = @"上个月";

} else if (deltaMinutes < (24 * 60 * 365.25)) {

dateContent = [NSString stringWithFormat:@"%d月前", (int)floor(deltaMinutes/(60 * 24 * 30))];

} else if (deltaMinutes < (24 * 60 * 731)) {

dateContent = @"去年";

} else {

dateContent = [NSString stringWithFormat:@"%i年前", (int)floor(deltaMinutes/(60 * 24 * 731))];

}

全部评论 (0)

还没有任何评论哟~