在我的机器上(区域设置美国),默认的“短”日期格式设置为“1/5/13”(月/日/年)。
在系统偏好设置中,我附加了一个星期编号,“1/5/13 1”。
我的问题是这段代码,我尝试将字符串转换为日期:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSDate *date = [dateFormatter dateFromString:@"1/5/13 1"];
NSLog(@"Date: %@", date);
在我的机器上打印:
Date: 2000-01-01 05:00:00 +0000
2000 ,甚至不接近 2013 。
是什么导致了这个问题?
答案 0 :(得分:8)
我迟到了这个讨论,并且已经看到了许多解决方案,但我看到它们的全部错误是两个不兼容的日期格式元素一起使用。您的原始方法失败,因为您尝试获取日期的字符串与NSDateFormatterShortStyle
提供的字符串不匹配。
如果您要评估一年中的一周,那么您必须使用当年的大写形式;这提供了“年度周”类日历。
让我们重新编写原始代码以包含新格式:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/YY w"];
NSDate *date = [dateFormatter dateFromString:@"1/5/13 1"];
NSLog(@"Date: %@", date);
请注意,我正在使用该年份的大写形式。一年中有一周,我得到了这个:
Date: 2013-01-05 08:00:00 +0000
和一年中的2周:
Date: 2013-01-12 08:00:00 +0000
和3:
Date: 2013-01-19 08:00:00 +0000
有道理,不是吗?日期中的日期增加7天,每个增量按一周中的一周增加。当然,时间已经过去了,但我们从未讨论过要在该领域进行评估的任何事情,是吗?
答案 1 :(得分:2)
NSDateComponents *cmp=[[[NSDateComponents alloc]init]autorelease];
[cmp setWeek:1];
NSCalendar *cal=[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *dte=[NSDate date];
NSDate *weekDate=[cal dateByAddingComponents:cmp toDate:dte options:0];
[dateFormatter setDateFormat:@"MM/dd/YY"];
NSString *strDate=[dateFormatter stringFromDate:weekDate];
NSLog(@"Date: %@", strDate);
答案 2 :(得分:-1)
您需要使用dateFromString
...
NSDateFormatter
方法
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm/dd/yyyy"];
NSDate *myDate = [dateFormatter dateFromString:@"1/5/2013"];
NSLog(@"Date: %@", myDate);
如果您想使用周数,请根据需要使用NSCalendar
和NSDateComponents
...(请参阅此代码段)
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSWeekCalendarUnit fromDate:date];
NSInteger week = [components week];
我希望这会有所帮助。