NSDateFormatter错误的时间 [英] Wrong time from NSDateFormatter

查看:154
本文介绍了NSDateFormatter错误的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我想从以下地址解析时间:

  NSString * longdate = @2011年3月27日8:38:38 PM 

我想解析这个日期,只输出时间部分w / hours + minutes + am / pm :

  //首先,将我们的字符串转换为NSDate 
NSDateFormatter * inFormat = [[NSDateFormatter alloc] init] ;
[inFormat setDateFormat:@MMM dd,yyyy HH:mm:ss aaa];
NSDate * date = [inFormat dateFromString:longdate];
[inFormat release];

//现在从日期转换为字符串
NSDateFormatter * outFormat = [[NSDateFormatter alloc] init];
[outFormat setDateFormat:@HH:mm aaa];
NSString * final = [outFormat stringFromDate:date];
[outFormat release];

NSLog(@original:%@ | final%@,longdate,final);

问题是最后的时间是错误的。我期待时间是下午8:38,而是下午12:38。



我只是想和我一样的时间,而且不打扰任何时区或地区。我在这里做错了什么?谢谢。

解决方案

发现问题。与时区无关,并且与日期格式化程序使用错误的格式代码有关。

  [inFormat setDateFormat:@ MMM dd,yyyy HH:mm:ss aaa]; 

应该是:

  [inFormat setDateFormat:@MMM dd,yyyy h:mm:ss aaa]; 

同样,outFormat的dateformat应该是:



< p $ p> [outFormat setDateFormat @h:mm aaa];

在此调整后,即使没有任何TimeZone调整,一切都可以正常运行。


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.

这篇关于NSDateFormatter错误的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆