Getting date from [NSDate date] off by a few hours

前端 未结 3 752
春和景丽
春和景丽 2020-11-21 07:36

I am using

NSDate *date = [NSDate date];

for getting the date, but the date I get is off by 2 hours.

3条回答
  •  [愿得一人]
    2020-11-21 07:52

    -(NSDate *)getDateInCurrentSystemTimeZone
    {
        NSDate* sourceDate = [NSDate date];
        NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    
        NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
        NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
        NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    
        NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
        return destinationDate;
    }
    

提交回复
热议问题