JoJo
JoJo

Reputation: 20115

Create NSDate from Unix timestamp

How do I create an NSDate from a Unix timestamp?

channel.startDate = [NSDate dateWithTimeIntervalSince1970:
(NSTimeInterval)[channelJson objectForKey:@"broadcastStartedTime"]];

I get this error:

104: error: pointer value used where a floating point value was expected

channels.startDate is an NSDate*. The value for the key "broadcastStartedTime" is a Javascript Number converted into an NSNumber or NSDecimalNumber by the SBJson parser library.

Upvotes: 44

Views: 26200

Answers (4)

Michael Dorner
Michael Dorner

Reputation: 20155

NSTimeInterval (which is unix timestmap) to NSDate conversion in Swift:

let timeInterval = NSDate().timeIntervalSince1970 // the the unix timestamp
NSDate(timeIntervalSince1970: timeInterval)

Upvotes: 1

Wayne Hartman
Wayne Hartman

Reputation: 18477

Try this instead:

NSNumber *startTime = channelJson[@"broadcastStartedTime"];
channel.startDate = [NSDate dateWithTimeIntervalSince1970:[startTime doubleValue]];

Your value is trapped in a pointer type of NSNumber. The dateWithTimeIntervalSince1970 method is expecting a primitive NSTimeInterval (which, under the covers, is a double).

Upvotes: 56

BJ Homer
BJ Homer

Reputation: 49034

Use -doubleValue:

// NSTimeInterval is just a typedef for double
NSTimeInterval interval = [[channelJson objectForKey:@"broadcastStartedTime"] doubleValue];
channel.startDate = [NSDate dateWithTimeIntervalSince1970:interval];

Upvotes: 7

Wevah
Wevah

Reputation: 28242

You need to unwrap the NSNumber:

channel.startDate = [NSDate dateWithTimeIntervalSince1970:[[channelJson objectForKey:@"broadcastStartedTime"] doubleValue]];

Upvotes: 4

Related Questions