本文介绍了dateFromComponents的意外结果:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码
NSCalendar *cal = [NSCalendar currentCalendar]; [cal setFirstWeekday:2]; [cal setMinimumDaysInFirstWeek:4]; NSDateComponents *comp = [[NSDateComponents alloc] init]; [comp setYear: 2012]; [comp setMonth:3]; [comp setDay: 12]; NSDate *date = [cal dateFromComponents:comp]; NSLog(@"date:%@",date);日志:
date:2012-03-11 23:00:00 +0000任何想法,为什么会发生这种情况以及如何避免 Tnx
Any Idea, why this happen and how to avoid Tnx
推荐答案我假设您在本地使用CET时区。这就是 [NSCalendar currentCalendar] 将用作时区。
I assume you are using the CET time zone locally. This is what the [NSCalendar currentCalendar] will use as a time zone then.
当您转储 NSDate 使用NSLog,您将以原始UTC格式获取日期。要使用本地格式打印日期,请查看 NSDateFormatter 类,该类具有 timeZone 属性:
When you dump a NSDate with NSLog, you will get the date in its raw UTC form. To print the date using a local format, look into the NSDateFormatter class, which has a timeZone property:
.... NSDate *date = [cal dateFromComponents:comp]; NSDateFormatter* fmt = [[NSDateFormatter alloc] init]; fmt.timeZone = [NSTimeZone defaultTimeZone]; // Probably not required NSLog(@"date:%@", [fmt stringFromDate:date]);更多推荐
dateFromComponents的意外结果:
发布评论