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.
Found the problem. Had nothing to do with timezones and everything to do with using the wrong formatting codes for the date formatter.
[inFormat setDateFormat:@"MMM dd, yyyy HH:mm:ss aaa"];
should be:
[inFormat setDateFormat:@"MMM dd, yyyy h:mm:ss aaa"];
Likewise, outFormat's dateformat should be:
[outFormat setDateFormat:@"h:mm aaa"];
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:
[outFormat setTimeZone:[NSTimeZone localTimeZone]];
You've got your timezones messed up. IIRC, NSDateFormatter
(by default) will parse stuff in the UTC timezone (+000), but dates are NSLog
ged in your current timezone. Or something like that.
Anyway, check your timezones.
NSString *longdate = @"2013-04-29 10:20 PM";
// First, convert our string into an NSDate
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setTimeZone:[NSTimeZone localTimeZone]];
[inFormat setDateFormat:@"yyyy-MM-dd hh:mm aa"];
NSDate *date = [inFormat dateFromString:longdate];
// Now convert from date back to a string
NSDateFormatter *outTimeFormat = [[NSDateFormatter alloc] init];
[outTimeFormat setDateFormat:@"hh:mm aaa"];
NSString *finalTime = [outTimeFormat stringFromDate:date];
NSDateFormatter *outDateFormat = [[NSDateFormatter alloc] init];
[outDateFormat setDateFormat:@"yyyy-MM-dd"];
NSString *finalDate = [outDateFormat stringFromDate:date];
NSLog(@"Date:%@ and Time :%@",finalDate,finalTime);