0

次のコードを使用して、文字列を dateFormatter に送信します。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-mm-dd hh:mm a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]];

NSDate *currentDate = [NSDate date];
NSCalendar* calendario = [NSCalendar currentCalendar];
NSDateComponents* components = [calendario components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate];

//make new strings
NSString *adjustedOpenDateString = [NSString stringWithFormat:@"%@-%ld-%ld %@", @"2013", (long)[components month], (long)[components day], openDateString];
NSString *adjustedCloseDateString = [NSString stringWithFormat:@"%@-%ld-%ld %@", @"2013", (long)[components month], (long)[components day],closeDateString];
NSLog(@"adjustedString %@", adjustedCloseDateString);  //<<<<---NSLOG1

//Convert strings to dates
NSDate *openDate = [dateFormatter dateFromString:adjustedOpenDateString];
NSDate *closeDate = [dateFormatter dateFromString:adjustedCloseDateString];

NSLog(@"BEFORE COMPONENTS open, now, close %@,%@,%@", openDate,[NSDate date], closeDate); //<<<<---NSLOG2

if ([self timeCompare:openDate until:closeDate]) {
    NSLog(@"OPEN-timeCompare");
} else {
    NSLog(@"CLOSED-timeCompare");
}

そして、現在の日付を正しく記録しているadjustedString NSLogを取得します。

adjustedString 2013-7-25 10:00 PM

しかし、文字列から変換された日付をログに記録すると、月が失われます... 7 月から 1 月に切り替わります

open, now, close 2013-01-25 13:00:00 +0000,2013-07-26 02:54:31 +0000,2013-01-26 04:00:00 +0000

なぜこれが起こるのですか?

4

2 に答える 2

3

フォーマット文字列が間違っています。月には「MM」を使用する必要があるため、次のように置き換えます。

[dateFormatter setDateFormat:@"yyyy-mm-dd hh:mm a"];

[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm a"];

Date Format Patterns、Unicode Technical Standard #35 をご覧ください。

于 2013-07-26T03:19:52.627 に答える
1

NSDateFormatter が日付フォーマット文字列に使用するUnicode Technical Standard #35@"yyyy-MM-dd hh:mm a"に従って、フォーマット文字列を切り替えます。小文字の「m」は分、大文字は月です。

于 2013-07-26T03:19:44.367 に答える