1

次のコードを使用して、日付をNSStringからNSDateに変換しようとしています

NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:@"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];

currMonth = 3;
currYear = 2012;
NSString *str = [NSString stringWithFormat:@"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"0"];
myDate = [dateformatter dateFromString:str];
NSLog(@"myStr: %@",str);
NSLog(@"myMonth: %2d",currMonth);
NSLog(@"myYear: %d",currYear);
NSLog(@"myDate: %@",myDate);

上記のコードは私に間違った日付を与えています。誰か助けてもらえますか?

4

3 に答える 3

3

あなたの出力は何ですか?NSDateはUTCであることに注意してください。

2012-03-01 00:00:00 (GMT+1)2012-02-39 23:00:00 (UTC)

別のヒント:

%02整数を先行ゼロでフォーマットします。

于 2012-04-13T09:29:44.750 に答える
1

これを試して:

-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSTimeInterval interval = 5 * 60 * 60;

NSDate *date1 = [dateFormat dateFromString:string];  
date1 = [date1 dateByAddingTimeInterval:interval];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];

return date1;
}

それがあなたに役立つかどうか教えてください:]

于 2012-04-13T09:37:43.780 に答える
0

試す

NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:@"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];

int currMonth = 3;
int currYear = 2012;
NSString *str = [NSString stringWithFormat:@"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"0"];

//SET YOUT TIMEZONE HERE
dateformatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"PDT"];
myDate = [dateformatter dateFromString:str];
NSLog(@"myStr: %@",str);
NSLog(@"myMonth: %2d",currMonth);
NSLog(@"myYear: %d",currYear);
NSLog(@"myDate: %@",myDate);
于 2012-04-13T09:37:38.320 に答える