NSDate formattieren => Juchuuuu!

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • NSDate formattieren => Juchuuuu!

    Hi,

    ich krieg vom Server einen Datum String welcher folgendermassen formatiert ist: @"yyyy-MM-dd". Nun ist die Anforderung, dass in die entsprechende Locale umformatiert werden soll.

    Quellcode

    1. NSString* birthDateString = person.birthdate;
    2. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    3. [formatter setDateFormat:@"yyyy-MM-dd"];
    4. NSDate* date = [formatter dateFromString:birthDateString];
    5. NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"yyyy-MM-dd" options:0
    6. locale:[NSLocale currentLocale]];
    7. [formatter setDateFormat:formatString];
    8. NSString *formattedDateString = [formatter stringFromDate:date];
    Alles anzeigen
    Geht aber nicht! Ich werd bekloppt!
  • Ein Gefrickel ich sachs Euch!

    Quellcode

    1. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    2. [formatter setDateFormat:@"yyyy-MM-dd"];
    3. NSDate* date = [formatter dateFromString: birthDateString];
    4. NSString *dateComponents = @"yyyy-MM-dd";
    5. NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:[NSLocale currentLocale]];
    6. NSArray *tmpSubstrings = [dateFormat componentsSeparatedByString:@"-"];
    7. NSString *tmpStr;
    8. NSRange r;
    9. if ([[tmpSubstrings objectAtIndex:0] length] == 0) {
    10. r.location = 1;
    11. r.length = [[tmpSubstrings objectAtIndex:1] length] - 1;
    12. tmpStr = [[tmpSubstrings objectAtIndex:1] substringWithRange:r];
    13. } else {
    14. r.location = 0;
    15. r.length = [[tmpSubstrings objectAtIndex:0] length] - 1;
    16. tmpStr = [[tmpSubstrings objectAtIndex:0] substringWithRange:r];
    17. }
    18. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    19. [dateFormatter setDateFormat:tmpStr];
    20. NSString *formattedDateString = [dateFormatter stringFromDate:date];
    21. NSString* localBirthDateString = [NSString presetEmptyString:formattedDateString];
    Alles anzeigen
  • hmm, habe mir gerade mal deinen Code gepackt und mal getestet, also bei mir wird brav das richtige Datumsformat ausgegeben wenn ich per

    Quellcode

    1. NSLog(@"%@", formattedDateString);

    anzeigen lasse, vorher birthDateString auf @"1973-10-05" gesetzt zum Testen.
    [window close]