문제

나는 단지 뭔가를 놓치고 있다고 확신합니다. 그러나 나는 nsdateformattershortstyle 스타일의 nsdate를 표시 할 때 4 자리 연도를 보여주는 방법을 찾으려고 며칠 동안 이것을 구글링했습니다. 해결책이 있으면 알려주세요. 다음은 지금 내가 사용하고있는 코드입니다.

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease ];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];

    // add label for birth
    UILabel *birthday = [[UILabel alloc] initWithFrame:CGRectMake(125, 10, 100, 25)];
    birthday.textAlignment = UITextAlignmentRight;
    birthday.tag = kLabelTag;
    birthday.font = [UIFont boldSystemFontOfSize:14];
    birthday.textColor = [UIColor grayColor];
    birthday.text = [dateFormatter stringFromDate:p.Birth];
도움이 되었습니까?

해결책

4 자리가 필요한 경우 설정하십시오 dateformat: 원하는 정확한 형식을 사용합니다. 단점은 자동 로케일 서식을 잃는다는 것입니다.

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];

...

birthday.text = [dateFormatter stringFromDate:p.Birth];

현지화가 필요한 경우 짧은 스타일의 날짜 형식을 수정 해보십시오.

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease ];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];

if ([[dateFormatter dateFormat] rangeOfString:@"yyyy"].location == NSNotFound) { 
    NSString *fourDigitYearFormat = [[dateFormatter dateFormat] stringByReplacingOccurrencesOfString:@"yy" withString:@"yyyy"]; 
    [dateFormatter setDateFormat:fourDigitYearFormat];             
}

Max MacLeod의 BugFix로 업데이트되었습니다

다른 팁

내가 한 것처럼 누군가가 여기에 우연히 발견되는 경우, 나는 현지화 된 날짜 형식의 2 자리 연도에 그런 일이 필요했고 이것은 정말 오래된 질문입니다. 여기에 내 해결책이 있습니다.

NSLocale*           curLocale = [NSLocale currentLocale];
NSString*           dateFmt   = [NSDateFormatter dateFormatFromTemplate: @"ddMMyyyy"
                                                                options: 0
                                                                 locale: curLocale];
NSDateFormatter*    formatter = [[[NSDateFormatter alloc] init] autorelease];
                    [formatter setDateFormat:dateFmt];
NSString*           retText = [formatter stringFromDate:refDate];

return retText;

어쩌면 누군가가 언젠가 그것을 사용할 수 있을지 ...

이것은 오래된 실이지만, Dave가 원했고 할 수 없었던 일을하려고했기 때문에 주어진 답변 중 어느 것도 올바른 것이 아니기 때문에 다음은 해결책이 있습니다 (누군가가 원하는 경우).

NSString *FormatString = [NSDateFormatter dateFormatFromTemplate:@"MM/dd/yyyy HH:mm" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:FormatString];
//Parse date here with the formater (like [formatter stringFromDate:date])
[formatter release];

KCFDateFormatterShortStyle은 "11/23/37"또는 "3:30 PM"과 같은 짧은 스타일, 일반적으로 숫자 만 지정합니다.

Mac OS X V10.3 이상에서 제공됩니다.

cfdateformatter.h에서 선언되었습니다.

원천

NSDateFormatterShortStyle은 4 자리 연도를 제공하지 않습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top