开发者

Objective-C: help me convert a timestamp to a formatted date/time

I'm really struggling to convert this timestamp to a nice formatted date string.

Here's the timestamp: "1316625985"

And here's the function I've made:

-(NSString*)timestamp2date:(NSString*)timestamp{
    NSString * timeStampString =timestamp;
    //[timeStampString stringByAppendingString:@"000"];   //convert to ms
    NSTimeInterval _interval=[timeStampString doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFor开发者_运维问答matter *_formatter=[[NSDateFormatter alloc]init];
    [_formatter setDateFormat:@"dd/MM/yy"];
    return [_formatter stringFromDate:date];
}

Trouble is, it keeps returning dates in 1972! (31/7/72) This is wrong, since it's a September 2011 date...

Can anyone suggest any solution?

Many thanks in advance,


Isn't epoch seconds since 1/1/1970? are you sure that you didn't leave the millisecond line in?

When I ran you're logic (without your line append 000 for ms), it worked. Here's what I did:

    NSString * timeStampString = @"1316641549";
    NSTimeInterval _interval=[timeStampString doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSLog(@"%@", date);

It outputted:

2011-09-21 17:46:14.384 Craplet[13218:707] 2011-09-21 21:45:49 +0000


Just divide your [timeStampString doubleValue] by a thousand like:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStampString doubleValue]/1000.0];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:@"dd/MM/yy"];
return [_formatter stringFromDate:date];

or try [timeStampString longLongValue]/1000.0 instead

Good Luck!


Did you check that the string (timestampString) and the double value (_interval) are the same, and that the doubleValue does really takes all the characters of your string into account?

Maybe the interpretation of the string into double crops the value?


Are you also sure that the timestamp you are interpretting is really a UNIX timestamp, meaning it counts the number of seconds elapsed since 01/01/1970 (and not days since 01/01/1970?… or not seconds but since another date?)

(Maybe give an example of the value of the timestamp you are trying to interpret)


You can pass [timeStampString doubleValue] directly into dateWithTimeIntervalSince1970: instead of converting it into an NSTimeInterval.

Also, try adding some NSLog statements to see what your values are at various points, that should help track down where the difference is.

Hope this helps!


While using NSInterval to get the interval, make sure the timestamp is in seconds and not milliseconds. If it is in milliseconds, just divide the NSInterval value by 1000 and then try formatting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜