我正在尝试使用以下代码将日期从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);
上面的代码给我错误的日期。谁能帮忙吗?
最佳答案
你的输出是什么?请记住,NSDate位于UTC中。2012-03-01 00:00:00 (GMT+1)
是2012-02-39 23:00:00 (UTC)
另一个提示:%02
用前导零格式化您的整数。
关于iphone - ios:字符串到日期的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10138271/