NSDate is not returning my local Time zone /default time zone of device

后端 未结 7 1969
孤城傲影
孤城傲影 2020-11-27 16:02

My local and default time zone is GMT +5 but when I get date and time by NSDate it return me GMT date and time.

For example the code and output from my code while

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 16:15

    Try this

    - (NSDate *) GetLocalDate {
    
        NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
        NSCalendar *theCalendar = [NSCalendar currentCalendar];
        theCalendar.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
        dayComponent = [[NSCalendar currentCalendar] components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    
        NSDate *localDate = [theCalendar dateFromComponents:dayComponent];
    
        return localDate;
    }
    
    - (void)viewDidLoad {
            [super viewDidLoad];
            NSLog(@"localDate : %@",[self GetLocalDate]);
    }
    

提交回复
热议问题