我从服务器接收日期格式为" /日期(1413374176217)/" 。我试过这个
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"]
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:date];
NSLog(@"dateFromString = %@",dateFromString);
但不起作用。
如何将其转换为字符串?
答案 0 :(得分:2)
试试这个。
NSString *actDate = @"/Date(1326067200000)/";
NSString *nDate = [[[[actDate componentsSeparatedByString:@"("] objectAtIndex:1] componentsSeparatedByString:@")"] objectAtIndex:0];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:([nDate doubleValue] / 1000)];
答案 1 :(得分:1)
您的字符串似乎是千分之一秒的unix时间戳。 假设你的意思是从服务器上获取该字符串,你可以这样做。
NSString * serverData = @"/Date(1413374176217)/";
NSString *timeString = [[serverData componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet]] componentsJoinedByString:@""];
double timeStamp = [timeString doubleValue];
NSTimeInterval interval = timeStamp/1000;
NSDate * date = [NSDate dateWithTimeIntervalSince1970:interval];
NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateFormat:@"dd.MM.yyyy"];
NSString * dateString =[formatter stringFromDate:date];
NSLog(@"%@", dateString);
答案 2 :(得分:0)
问题是返回的值是从纪元开始的毫秒数,而不是秒。 1413374176217
大约是当前Unix timeStamp的1000倍。试试这样的事情
- (NSDate *)dateFromStringInMilliseconds:(NSString *)millisecondsStr
{
// Get our string value in seconds instead of milliseconds
NSTimeInterval unixTimestamp = [millisecondsStr doubleValue] / 1000.0;
// Convert to an actual date.
NSDate *actualDateVal = [NSDate dateWithTimeIntervalSince1970:unixTimestamp];
// For good measure you could throw in an assert here if you wanted.
// NSAssert(actualDateVal, @"actualDateVal equals nil this should never happen");
/* If you don't have the assert you could just do the below instead of creating actualDateVal.
* return [NSDate dateWithTimeIntervalSince1970:unixTimestamp];
*/
return actualDateVal;
}
然后您可以将其称为NSDate *date = [self dateFromStringInMilliseconds:@"1413374176217"];