ubiAle
ubiAle

Reputation: 445

iOS get Time from Date

I'm developing an application and I need to parse a Tweet timestamp that actually is a string like this:

"Mon, 17 Oct 2011 10:20:40 +0000"

However what I need it is only the time. So what I'm trying to get it is:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:@"HH:mm"];
 NSDate *date = [dateFormatter dateFromString:timestamp];

but when I try to print the Date with NSLog the output is (null) and I don't understand why. What I need, if it is possible, is to create a date object only with the time. Indeed later on I need to compare different dates but I care only about the time. It is not important if the date are different because of the day, month or year, the important is that I can compare them with the "timeIntervalSinceDate" to get the difference in seconds.

Any help will be really appreciated.

Thanks Ale

Upvotes: 1

Views: 6667

Answers (2)

rckoenes
rckoenes

Reputation: 69499

NSDATE is al full date object, it needs a date en time. You can use NSDateFormatter to only display the time, but you will need to parse the full string to get the NSDate object.

Here some code you can use:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Mon, 11 Jul 2011 00:00:00 +0200
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"EN"] autorelease]];
[dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss ZZZZ"];

NSDate *date = [dateFormatter dateFromString: timestamp];
[dateFormatter release], dateFormatter = nil;

You need to set the local to make sure it read the timestamp in the correct language. Also alloced the dateFormatter outside any loops and release it after you're done with the loop.

Upvotes: 6

wbyoung
wbyoung

Reputation: 22493

Look at NSDateComponents. You should be able to create a date from components. You'll have to parse the timestamp yourself, though (which should be easy — just split on the colon and grab the number from each component).

Upvotes: 0

Related Questions