NSDateFormatter not working to set setTimeZone

后端 未结 2 1723
谎友^
谎友^ 2021-01-28 15:45

I am trying to know the difference between two dates (Including days,hours,minutes and seconds). For that I am using below code, but It\'s not working.

+ (void)         


        
2条回答
  •  野性不改
    2021-01-28 16:34

    [NSDate date] is taking default timezone as GMT. so, I am unable to set my local timezone to date.

    While knowing the difference between GMT OFFset to local , I am able to get the difference between two dates sucessfully.

    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];
        NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
        [outputFormatter setAMSymbol:@"AM"];
        [outputFormatter setPMSymbol:@"PM"];
        [outputFormatter setLocale:[NSLocale currentLocale]];
        [outputFormatter setDateFormat:@"MM/dd/yyyy hh:mm a"];
    
     NSDate *gameDate = [outputFormatter dateFromString:gameTime];
     NSDate* gameDestinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:gameDate];
    //    NSLog(@"gameDate=%@",gameDate);
    NSCalendar *gregorian = [[NSCalendar alloc]                 initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
    NSDateComponents *components = [gregorian components:unitFlags                           fromDate:destinationDate toDate:gameDestinationDate options:0];
    NSInteger days = [components day];
    NSInteger hours = [components hour];
    NSInteger seconds = [components second];
    NSInteger minutes = [components minute];
    
    return ([NSString stringWithFormat:@"%01ddays:%02dhrs:%02dmins:%02dsec",abs(days),abs(hours), abs(minutes), abs(seconds)]);
    

提交回复
热议问题