Reputation: 523
The results of destinationDate and components differ. how do i solve this problem?
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSDate* sourceDate = [NSDate date];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit |
NSHourCalendarUnit |
NSMinuteCalendarUnit|
NSSecondCalendarUnit) fromDate:destinationDate];
NSLog(@"%@", destinationDate);
NSLog(@"%@", components);
2013-04-24 19:27:09 +0000
Calendar Year: 2013 Month: 4 Leap month: no Day: 25 Hour: 4 Minute: 27 Second: 9
Upvotes: 0
Views: 4231
Reputation: 130102
The date (destinationDate
) is printed in GMT. However, the date components are not because the calendar is created with the local time zone.
If you try it with calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]
you will get the same result from both. Otherwise you'll get the difference added twice (first time by your code, second time by the calendar)
Actually, your code doesn't make a lot of sense. NSDate
should never be modified by time zone because it doesn't hold any time zone information. A NSDate
always represents a specific moment in time, independent on time zones. Transform the date only if you want to convert it to a string - and when you do, use NSCalendar
or NSDateFormatter
with the correct time zone set.
The following code is enough to print out the date with the system (default) time zone,
NSDate* sourceDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit |
NSHourCalendarUnit |
NSMinuteCalendarUnit|
NSSecondCalendarUnit) fromDate:destinationDate];
NSLog(@"%@", sourceDate);
NSLog(@"%@", components);
Upvotes: 5
Reputation: 8460
NSDateComponents
always gives the date in the form of GMT so simply place like below you'l get the current date.
NSDateComponents *components = [calendar components:(NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit |
NSHourCalendarUnit |
NSMinuteCalendarUnit|
NSSecondCalendarUnit) fromDate:[NSDate date]];
replace destinationDate
with [NSDate date]
.
output:
2013-04-24 16:05:08 +0000
<NSDateComponents: 0x7e3e5b0>
Calendar Year: 2013
Month: 4
Day: 24
Hour: 16
Minute: 5
Second: 8
Upvotes: 1