9

私は何かが欠けていると確信しています。しかし、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

4 に答える 4

12

私がやったように誰かがここでつまずいた場合に備えて、ローカライズされた日付形式で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;

多分誰かがいつかそれを使うことができるでしょう...

于 2011-03-18T02:24:12.547 に答える
11

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 によるバグ修正で更新

于 2009-05-10T16:03:50.633 に答える
1

これは古いスレッドですが、私はデイブが望んでいたこととできなかったことを実行しようとしていたため、そして与えられた答えのどれも正しくなかったため、ここに解決策があります(誰かが同じことをしたい場合に備えて):

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];
于 2012-03-29T14:58:20.390 に答える
0

kCFDateFormatterShortStyle 「11/23/37」や「3:30pm」など、通常は数値のみの短いスタイルを指定します。

Mac OS X v10.3 以降で利用できます。

CFDateFormatter.h で宣言されています。

ソース

NSDateFormatterShortStyle は 4 桁の年を表示していないようです。

于 2009-05-10T15:55:17.540 に答える