Reputation: 2307
I have a table in mysql that records the timestamp when the thread gets stored, but I cant seem to display the correct time on the app.
The date ([dict objectForKey:@"AT_Date"]
) comes back with 2015-06-15 15:12:04, but I don't know if this correct, as I thought it's supposed to return a long number. And my final date when converted back to local date always outputs 1970-01-01 00:33:35 +0000, which is wrong. Why is this happening?
Code:
if((NSNull *)[dict objectForKey:@"AT_Date"] != [NSNull null]){
NSString *timestampString = [dict objectForKey:@"AT_Date"];
double timestampDate = [timestampString doubleValue];
at_Date = [NSDate dateWithTimeIntervalSince1970:timestampDate];
if (counter == 1) {
lastDateForumActivity = timestampString;
}
}
Upvotes: 0
Views: 56
Reputation: 4745
The error:
When you take the doubleValue
from timestampString
it should take the part of the string which can be converted to a double
and this would just be 2015. Then you create an NSDate
for 2015 seconds after 01-01-1970 00:00:00
. One hour is 3600 seconds, half an hour 1800 seconds, so the time of about 33 min after midnight looks plausible.
How to do it:
Create an NSDateFormatter
and set it up so that it matches what you get from the query. For example:
NSString *timestampString = @"2015-06-15 15:12:04"; // [dict objectForKey:@"AT_Date"];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale:locale];
NSTimeZone *tz = [NSTimeZone timeZoneWithName:@"UTC"];
[df setTimeZone:tz];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *timestampDate = [df dateFromString:timestampString];
NSLog(@"date = %@", timestampDate);
// outputs: "... date = 2015-06-15 15:12:04 +0000"
Upvotes: 2