سؤال

I want to get a NSDate object with NSDateComponents but the hour of the NSDate is 1 hour lower then in the components.

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setLocale:[NSLocale currentLocale]];
[cal setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *hourComp = [[NSDateComponents alloc] init];
hourComp.timeZone = [NSTimeZone localTimeZone];
[hourComp setHour:18];

NSLog(@"%@",hourComp);
NSLog(@"%@",[cal dateFromComponents:hourComp]);
NSLog(@"%@",[NSDate date]);

Console Output:

2012-04-10 19:10:57.505 TestDate[9861:f803] <NSDateComponents: 0x6b6ad30>
TimeZone: Europe/Berlin (CEST) offset 7200 (Daylight)
Hour: 18
2012-04-10 19:10:57.507 TestDate[9861:f803] 0001-01-01 17:06:32 +0000
2012-04-10 19:10:57.508 TestDate[9861:f803] 2012-04-10 17:10:57 +0000

What I want is 18:xx:xx

هل كانت مفيدة؟

المحلول

I note that you're in Europe, and one hour ahead of GMT. When you set the date to 18:xx it thinks you are setting it in Europe, and so it subtracts one hour before storing it in GMT. When you print it out, you're not asking it to be formatted for local time, so it's giving you GMT, which is 17:xx.

You need to use an NSDateFormatter, and set its locale and time zone - just as you did with the NSCalendar object - and then call stringFromDate on it, passing the date you've created.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top