Wrong time from NSDateFormatter

2019-03-02 09:36发布

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.

4条回答
一夜七次
2楼-- · 2019-03-02 09:48

You've got your timezones messed up. IIRC, NSDateFormatter (by default) will parse stuff in the UTC timezone (+000), but dates are NSLogged in your current timezone. Or something like that.

Anyway, check your timezones.

查看更多
我只想做你的唯一
3楼-- · 2019-03-02 09:51

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.

查看更多
叛逆
4楼-- · 2019-03-02 09:54
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);
查看更多
我命由我不由天
5楼-- · 2019-03-02 10:02

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]];
查看更多
登录 后发表回答