unexpected result of dateFromComponents:

夙愿已清 提交于 2019-12-02 06:14:21

问题


the following code

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);

logs:

date:2012-03-11 23:00:00 +0000

Any Idea, why this happen and how to avoid Tnx


回答1:


I assume you are using the CET time zone locally. This is what the [NSCalendar currentCalendar] will use as a time zone then.

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]);



回答2:


set timezone

NSCalendar *cal = [NSCalendar currentCalendar];

[cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];



回答3:


When you call dateFromComponents: you lose all of the timezone and calendar information and are left an NSDate object that contains the moment in time your date components represent, but nothing else. When you use NSLog on your NSDate object, that moment in time is converted to a time in UTC and rendered as a human readable string.

You need to provide more info about what you're trying to achieve to be able to answer your second question of how to avoid this.



来源:https://stackoverflow.com/questions/9751249/unexpected-result-of-datefromcomponents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!