I am creating a date from [NSdate date] and saving it to plist, Here is how I am creating a date
- (void)applicationWillResignActive:(UIApplication *)application
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// [gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSMinuteCalendarUnit)fromDate:[NSDate date]];
NSInteger day = [weekdayComponents day];
NSInteger month = [weekdayComponents month];
NSInteger year = [weekdayComponents year];
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
[timeZoneComps setDay:day];
[timeZoneComps setMonth:month];
[timeZoneComps setYear:year];
[timeZoneComps setHour:00];
[timeZoneComps setMinute:00];
[timeZoneComps setSecond:01];
NSDate *date = [gregorian dateFromComponents:timeZoneComps];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"file.plist"];
NSMutableDictionary *d = [NSMutableDictionary new];
[d setObject:date forKey:@"my-date"];
[d writeToFile:filePath atomically:YES];
}
I have tested few cases
Case 1: without setting timezone to NSCalendar object gregorian above(by default it will take local time zone) and setting time zone in device to india, I saved the date to plist and this is what I got
NSLog of date shows CurrentDate:2014-07-08 18:30:01 +0000
Case 2: Now setting device time zone to san jose USA
NSLog of date shows 2014-07-09 07:00:01 +0000
Case 3: Setting timezone of NSCalendar object, gregorian above to "UTC", and setting time zone in device to India, this is what I got in plist
NSLog of date shows 2014-07-09 00:00:01 +0000
Case 4: Setting device time to san jose USA
NSLog of date shows 2014-07-09 00:00:01 +0000
Can anybody please explain me what is happening in all these cases.
Regards Ranjit.
NSLog(@"date=%@", date);
? – trojanfoeNSLog()
call will use[NSDate description]
to print the date, which is the date in UTC. Therefore you have proved the effects of setting dates with specific time zones and saving them in UTC, which is why the dates change in the plist. – trojanfoe