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 回答