2

以下代码

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

4

3 回答 3

2

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.

于 2012-03-17T15:45:12.847 回答
2

我假设您在本地使用 CET 时区。这就是[NSCalendar currentCalendar]届时将用作时区的内容。

当您NSDate使用 NSLog 转储 a 时,您将获得原始 UTC 格式的日期。要使用本地格式打印日期,请查看NSDateFormatter具有以下timeZone属性的类:

....
NSDate *date = [cal dateFromComponents:comp];
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
fmt.timeZone = [NSTimeZone defaultTimeZone]; // Probably not required
NSLog(@"date:%@", [fmt stringFromDate:date]);
于 2012-03-17T15:36:39.597 回答
2

设置时区

NSCalendar *cal = [NSCalendar currentCalendar];

[cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
于 2012-03-17T15:40:40.310 回答