2

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

mica
  • 3,898
  • 4
  • 34
  • 62
  • duplicate of [Why NSCalendar's dateFromComponents returns wrong date?](http://stackoverflow.com/questions/4322687/why-nscalendars-datefromcomponents-returns-wrong-date) – Parag Bafna Mar 17 '12 at 15:57

3 Answers3

2

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]);
Krumelur
  • 31,081
  • 7
  • 77
  • 119
2

set timezone

NSCalendar *cal = [NSCalendar currentCalendar];

[cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
Parag Bafna
  • 22,812
  • 8
  • 71
  • 144
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.

grahamparks
  • 16,130
  • 5
  • 49
  • 43
  • Actually it's quite the opposite - you don't lose any timezone information when using dateFromComponents, it in fact takes timezone into account and gives you back a date that makes sense to your *local* timezone (by default). Essentially if you create components with Today as the date and 16:00 as time, the date created will be 16:00 local time, unless you use a NSCalendar with GMT set as timezone. – strangetimes May 07 '17 at 13:07
  • @strangetimes I don't think we disagree, you're just looking at it a different way. – grahamparks May 12 '17 at 10:59