简体   繁体   English

使用NSDateFormatter将NSString解析为NSDate

[英]Parsing NSString to NSDate using NSDateFormatter

I have such string: "Tue, 22 Oct 2013 1:59 pm EEST" i am trying to set these parsing rules: 我有这样的字符串:“ TEST,2013年10月22日,美国东部时间下午1点59分”,我正在尝试设置以下解析规则:

[formatter setDateFormat: @"EEE, dd MMM yyyy hh:mm a z"];

but this returns nil when i perform: 但这在我执行时返回nil

[formatter dateFromString: @"Tue, 22 Oct 2013 1:59 pm EEST"];

What's the right regular expression for such format? 这种格式正确的正则表达式是什么?

 NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"EEE, dd MMM yyyy hh:mm a zzz"];
    [formatter setLocale:locale];
    NSDate* date = [formatter dateFromString:@"Tue, 22 Oct 2013 1:59 PM EEST"];
    NSLog(@"date: %@",date);

O/P:-date: 2013-10-22 10:59:00 +0000

hh is a padded hour ("01" in your case) but your string doesn't have padded hours (just "1" ) so it should be just h instead. hh是带填充小时(在您的情况下为“ 01”),但是您的字符串没有带填充小时(仅为“ 1”),因此应改为h

You can see a practical examples of the different formatting components below (output from this GitHub gist ). 您可以在下面看到不同格式组件的实际示例( 此GitHub gist的输出)。 The date being formatted is 1987-08-27 15:24:03 格式化的日期是1987-08-27 15:24:03

format  result
--------------
    yy  87
  yyyy  1987
     M  8
    MM  08
   MMM  Aug
  MMMM  August
    dd  27
    HH  15
    hh  03    // <--.
     h  3     // <--'--- note the difference
     a  PM
    mm  24
     m  24
    ss  03
     s  3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM