iPhone NSDateFormatter Timezone Conversion

前端 未结 6 1274
终归单人心
终归单人心 2020-12-03 01:15

I am trying to create a formatter that will convert the date format shown to an NSDate object:

NSString *dateStr = @\"2010-06-21T19:00:00-05:00\";
NSDateForm         


        
相关标签:
6条回答
  • 2020-12-03 01:22

    This is the default time format I got from a Sinatra ActiveRecord backend. Here is my solution.

    -(NSDate *) dateFromString:(NSString *)string{
        NSMutableString * correctedDateString = [[NSMutableString alloc] initWithString:string];
        [correctedDateString deleteCharactersInRange: NSMakeRange(22, 1)];
    
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
    
        return [formatter dateFromString:correctedDateString];
    }
    
    0 讨论(0)
  • 2020-12-03 01:24

    To process the time zone with the colon in it, you just need to use 5 'Z's. This is a pretty common date format, the ISO-8601 format. This will only work on iOS 6.x+

    -(NSDate *) dateFromString:(NSString *)string {
    
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
    
        return [formatter dateFromString:string];
    }
    
    0 讨论(0)
  • 2020-12-03 01:25

    Honestly, you'll just have to change the source data (removing the colon) before running it through the formatter. Your original date string is non-standard and none of the time zone format strings will work properly on it.

    You can see the valid inputs on unicode.org.

    ZZZ e.g. "-0500"

    ZZZZ e.g. "GMT-05:00"

    Nothing for "-05:00"

    0 讨论(0)
  • 2020-12-03 01:25

    This is the only solution that worked for me:

    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
    
    0 讨论(0)
  • 2020-12-03 01:29

    May be I missed something but ZZ worked for me. I used:

    @"yyyy-MM-dd'T'HH:mm:ss.SSSZZ"
    

    for

    2014-02-27T08:00:00.000+04:00
    
    0 讨论(0)
  • 2020-12-03 01:30

    5 ZZZZZ - heres a category I wrote with some sample of GMT to BST

    https://github.com/clearbrian/NSDateFormatter_ISO_8601

    0 讨论(0)
提交回复
热议问题