2

日付から時間、分、および午前/午後を抽出しようとしましたが、NULL 出力が得られます。コードを以下に示します。確認してください。

NSString *dateStr=@"29/07/2013 02:00am";
NSDateFormatter * formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mmaa"];
NSDate *date=[formatter dateFromString:dateStr];
NSString *finalDate=[formatter stringFromDate:date];
NSLog(@"%@",finalDate);

よろしくお願いします

4

2 に答える 2

4

あなたは非常に近いですが、元の文字列を解析する前にその日付形式を指定し、作成する前に出力の日付形式を設定する必要があります。

NSString *dateStr=@"29/07/2013 02:00am";

// Create a date formatter
NSDateFormatter * formatter=[[NSDateFormatter alloc] init];

// As rmaddy pointed out, you should set the locale:
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

// Set the date format for the input string
[formatter setDateFormat:@"dd/MM/yyyy hh:mma"];

// Create the NSDate from the string
NSDate *date=[formatter dateFromString:dateStr];

// Set the date format for the output string
[formatter setDateFormat:@"hh:mma"];

// Create the output string
NSString *finalDate=[formatter stringFromDate:date];
NSLog(@"%@",finalDate);  //  Output is: 02:00AM
于 2013-07-29T03:28:14.983 に答える
-1
- (void) dateformat{
    NSDate *today = [[NSDate alloc] init];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [gregorian components:NSHourCalendarUnit|NSMinuteCalendarUnit
                                                       fromDate:today];


    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setDateStyle:NSDateFormatterNoStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *dateString = [formatter stringFromDate:today];
    NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
    NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
    BOOL is24hTime = (amRange.location == NSNotFound && pmRange.location == NSNotFound);

    if (is24hTime == NO ) {

        NSString *meridiem = (amRange.location == NSNotFound)?@"PM":@"AM";
        NSLog(@"%d:%d %@",components.hour,components.minute,meridiem);
    }

}
于 2013-07-29T03:54:39.710 に答える