格式化后NSDateFormatter错误的string
我通过一个string参数tempDateString以[日月年]格式(例如01 05 2005)接收date:
NSLog(@"tempdatestring %@", tempDateString); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd MM YYYY"]; NSDate *dayDate = [dateFormatter dateFromString:tempDateString]; NSLog(@"daydate %@", dayDate);
我的问题是,这两个日志不匹配。 输出是:
tempdatestring 04 10 2012 daydate 2011-12-24 22:00:00 +0000
我应该在date格式化程序的date格式中更改什么来获取最佳date?
2个问题
- 你的格式是错误的是
@"dd MM yyyy"
区分大小写 -
使用时区获取正确的值[GMT值]
NSString *tempDateString=@"04 10 2012" ; NSLog(@"tempdatestring %@", tempDateString); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; [dateFormatter setDateFormat:@"dd MM yyyy"]; NSDate *dayDate = [dateFormatter dateFromString:tempDateString]; NSLog(@"daydate %@", dayDate);
做这个:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd MM yyyy"]; NSDate *dayDate = [dateFormatter dateFromString:tempDateString]; NSLog(@"daydate %@", dayDate); NSString *strDate = [dateFormatter stringFromDate:dayDate]; NSLog(@"strDate :%@",strDate);
当使用%@
格式说明符时,将使用在提供的对象上调用的-description
方法的返回值。
NSDate
的描述方法以特定的方式输出其值。
你真正的问题是,你的date格式string是不正确的 – 它应该是dd MM yyyy
。
我坚持在一个示例Xcode项目中:
NSString *s = @"04 11 2012"; NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"dd MM yyyy"]; NSDate *d = [df dateFromString:s]; NSDateComponents *c = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:d]; NSLog(@"%@", c);
它给了我以下输出:
2012-10-04 01:53:24.320 dftest[59564:303] <NSDateComponents: 0x100113e70> Calendar Year: 2012 Month: 11 Leap month: no Day: 4
NSDateFormatter *form = [[NSDateFormatter alloc] init]; [form setDateFormat:@"dd MM yyyy"]; form.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:-7200.0]; NSDate *dayDate = [form dateFromString:@"05 10 2012"]; NSLog(@"daydate %@", dayDate); NSString *strDate = [form stringFromDate:dayDate]; NSLog(@"strDate %@",strDate);
将date格式更改为@"dd MM yyyy"
。 在此之后,dateFromString仍然可以parsing错误的date(在我的情况下是昨天21-00)。 为了避免这种情况,我在DateFormatter中设置了TimeZone:
form.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:-7200.0];
-7200.0是我的时区,你应该改变你的(“0”设置为格林威治)。 在这个日志看起来像:
daydate 2012-10-05 02:00:00 +0000 strDate 05 10 2012