NSDate conversion utilities

// Gets UTC NSDate from DateTime(.Net/WCF).

 

+ (NSDate *)fromDateTime:(NSString *)dateTime {
    NSDate *utcDate;
    if ([dateTime isMemberOfClass:[NSNull class]]) {
        utcDate = nil;
    } else {
        NSInteger offset = [[NSTimeZone timeZoneWithName:@"UTC"] secondsFromGMT];
        utcDate = [[NSDate dateWithTimeIntervalSince1970:[[dateTime substringWithRange:NSMakeRange(6, 10)] intValue]] dateByAddingTimeInterval:offset];
    }
    
    return utcDate;
}

// Converts NSDate to UTC DateTime(.Net/WCF).

- (NSString *)toDateTime {
    NSDateFormatter *utcFormatter = [[NSDateFormatter alloc] init];
    [utcFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    
    return [NSString stringWithFormat:@"/Date(%.0f000%@)/", [self timeIntervalSince1970],[utcFormatter stringFromDate:self]];
}


 

// Converts UTC NSDate to local time.

- (NSString *)utcToLocalTime {
    // offset second
    NSInteger seconds = [[NSTimeZone systemTimeZone] secondsFromGMT];
    
    NSDateFormatter *localTimeFormatter = [[NSDateFormatter alloc] init];
    [localTimeFormatter setDateFormat:@"MM/dd/yyyy HH:mm"];
    [localTimeFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: seconds]];
    
    return [localTimeFormatter stringFromDate:self];
}



原文地址:https://www.cnblogs.com/riskyer/p/3278105.html