将长格式日期转换为 iOS 中的 NSDate?

Convert date in long format to NSDate in iOS?

我得到的日期是长格式的“1425551087194”。我怎样才能将它转换成 NSDate 并显示正常的 "mm-dd-yyyy" 格式。

我试过下面的代码,输出也添加在这里

方法一:

    NSString * timeStampString =@"1425551087194";
    NSTimeInterval _interval=[timeStampString longLongValue];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:_interval];
    NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
    [_formatter setDateFormat:@"dd.MM.yyyy"];
    NSString *_date=[_formatter stringFromDate:date];
    NSLog(@"%@",_date);

输出是:07.02.47189

方法二:

NSString * timeStampString =@"1425551087194";
NSTimeInterval _interval=[timeStampString longLongValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:@"dd.MM.yyyy"];
NSString *_date=[_formatter stringFromDate:date];
NSLog(@"%@",_date);

输出为:08.12.47143

请帮忙 预期输出是当前日期。

试试这个

double getDate=1421112600996; // here replace your value
NSTimeInterval seconds = getDate / 1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
NSLog(@"ans : %@",date);    // your get answer like  ans :  2015-01-13 01:30:00 +0000

另一个转换

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];  // here replace your format dd.MM.yyyy
NSLog(@"result: %@", [dateFormatter stringFromDate:date]);
result: 2015-01-13 07:00:00 AM

除此之外一切似乎都是正确的

NSTimeInterval _interval=[timeStampString doubleValue]; //use double conversion instead of longlong
 NSDate *date = [NSDate dateWithTimeIntervalSinceNow:_interval/1000];//converting time interval to seconds
NSString * timeStampString =@"1304245000";
NSTimeInterval _interval=[timeStampString doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:@"dd.MM.yyyy"];
NSString *_date=[_formatter stringFromDate:date];