我正在尝试使用以下代码将我的日期从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);
上面的代码给了我错误的日期。有人可以帮忙吗?
答案 0 :(得分:3)
你的输出是什么?请记住,NSDate是UTC格式。
2012-03-01 00:00:00 (GMT+1)
是2012-02-39 23:00:00 (UTC)
另一个提示:
%02
使用前导零格式化整数。
答案 1 :(得分: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;
}
告诉我它是否有助于你:]
答案 2 :(得分: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);