我有一个时间戳如下。它采用字符串格式 “/日期(1402987019190 + 0000)/” 我想将其转换为NSDate。有人可以帮助我进入这个吗?
答案 0 :(得分:1)
使用dateWithTimeIntervalSince1970:,
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
NSLog(@"%@", date);
使用此函数将字符串转换为时间戳Ref。 https://stackoverflow.com/a/932130/1868660
-(NSString *)dateDiff:(NSString *)origDate {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"EEE, dd MMM yy HH:mm:ss VVVV"];
NSDate *convertedDate = [df dateFromString:origDate];
[df release];
NSDate *todayDate = [NSDate date];
double ti = [convertedDate timeIntervalSinceDate:todayDate];
ti = ti * -1;
if(ti < 1) {
return @"never";
} else if (ti < 60) {
return @"less than a minute ago";
} else if (ti < 3600) {
int diff = round(ti / 60);
return [NSString stringWithFormat:@"%d minutes ago", diff];
} else if (ti < 86400) {
int diff = round(ti / 60 / 60);
return[NSString stringWithFormat:@"%d hours ago", diff];
} else if (ti < 2629743) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:@"%d days ago", diff];
} else {
return @"never";
}
}
答案 1 :(得分:1)
如果我正确理解了您的意思,您需要使用给定格式解析字符串中的时间戳。 您可以使用正则表达式来提取时间戳值。
NSString * timestampString = @"/Date(1402987019190+0000)/";
NSString *pattern = @"/Date\\(([0-9]{1,})\\+0000\\)/";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:timestampString options:0 range:NSMakeRange(0, timestampString.length)];
NSRange matchRange = [textCheckingResult rangeAtIndex:1];
NSString *match = [timestampString substringWithRange:matchRange];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[match intValue];
NSLog(@"%@", date);