I have a string that I want to parse the time from:
NSString *longdate = @"Mar 27, 2011 8:38:38 PM";
I want to parse this date and output just the time portion w/ hours+minutes+am/pm:
// First, convert our string into an NSDate
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, yyyy HH:mm:ss aaa"];
NSDate *date = [inFormat dateFromString:longdate];
[inFormat release];
// Now convert from date back to a string
NSDateFormatter *outFormat = [[NSDateFormatter alloc] init];
[outFormat setDateFormat:@"HH:mm aaa"];
NSString *final = [outFormat stringFromDate:date];
[outFormat release];
NSLog(@"original: %@ | final %@", longdate, final);
The problem is the final time is wrong. I expect the time to be 8:38 PM, but instead I get 12:38 PM.
I just want to get the same hour out that I put it, and not bother w/ any time zones or locales. What am I doing wrong here? Thanks.
You've got your timezones messed up. IIRC,
NSDateFormatter
(by default) will parse stuff in the UTC timezone (+000), but dates areNSLog
ged in your current timezone. Or something like that.Anyway, check your timezones.
Found the problem. Had nothing to do with timezones and everything to do with using the wrong formatting codes for the date formatter.
should be:
Likewise, outFormat's dateformat should be:
After this adjustment everything works fine even w/o any TimeZone adjustments.
As Dave said, check your time zones. You can tell the date formatter to use your current time zone as well: