dateFromComponents的意外结果: [英] unexpected result of dateFromComponents:
本文介绍了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.
当您转储<$时c $ c> 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的意外结果:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文