我正在接收来自API
的聊天数据,并返回该消息的日期,如下所示:
30 minutes ago
1 hour ago
2 weeks ago
... etc
但是在JSQMessage中只需要NSDate
,我搜索并找不到一种动态的方式将其转换为NSDate
而没有特定的格式
JSQMessage* message = [[JSQMessage alloc] initWithSenderId:@"3" senderDisplayName:@"Name" date:@"" text:@"msg"];
非常感谢任何帮助。
答案 0 :(得分:1)
最好更改API响应。或者,您可以使用以下功能。
-(void)getLocationDetails:(NSString *)strDiffFrmAPI{
NSDate *dateActual;
if ([strDiffFrmAPI isEqualToString:@"30 minutes ago"]) {
dateActual = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitMinute
value:-30
toDate:[NSDate date]
options:0];
}
else if ([strDiffFrmAPI isEqualToString:@"1 hour ago"]){
dateActual = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitHour
value:-1
toDate:[NSDate date]
options:0];
}
else if ([strDiffFrmAPI isEqualToString:@"2 weeks ago"]){
dateActual = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay
value:(-7*2)
toDate:[NSDate date]
options:0];
}
}
我认为这不应该是一个好方法。如果从API获取Date的时间戳值,则会更好。
答案 1 :(得分:0)
我这样手动完成,因为我无法控制API
- (int) getCountFromDisplayDate : (NSString*) date {
NSString* number = @"";
for (int i = 0;i < date.length;i ++)
if ([date characterAtIndex:i] == ' ')
break;
else
number = [NSString stringWithFormat:@"%@%c",number,[date characterAtIndex:i]];
if ([number intValue])
return [number intValue];
return 0;
}
- (NSDate*) dateForIndexPath:(NSIndexPath*) indexPath {
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: @"MM/dd/yyyy"];
NSString* displayDate= _chat[indexPath.item][@"DisplayDate"];
NSString* whatWeDisplay = @"";
if ([displayDate containsString:@"ago"]) {
int count = [self getCountFromDisplayDate : displayDate] * -1;
if ([displayDate containsString:@"second"]) {
whatWeDisplay = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:count]];
}
else if ([displayDate containsString:@"minute"]) {
whatWeDisplay = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:count * 60]];
}
else if ([displayDate containsString:@"hour"]) {
whatWeDisplay = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:count * 60 * 60]];
}
else if ([displayDate containsString:@"day"]) {
whatWeDisplay = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:count * 24 * 60 * 60]];
}
else if ([displayDate containsString:@"week"]) {
whatWeDisplay = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:count * 7 * 24 * 60 * 60]];
}
else if ([displayDate containsString:@"month"]) {
whatWeDisplay = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:count * 30 * 24 * 60 * 60]];
}
else if ([displayDate containsString:@"year"]) {
whatWeDisplay = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:count * 365 * 30 * 24 * 60 * 60]];
}
}
else
whatWeDisplay = displayDate;
NSDate* theDate = [dateFormatter dateFromString:whatWeDisplay];
if (!theDate) {
return [NSDate date];
}
return theDate;
}