NSDate 时差8小时解决方法

我们用[NSDate date]获取的是GMT时间,这个时间和北京时间相差8个小时,下面展示几种方法解决这个问题

//方法一
- (void)date
{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    NSLog(@"%@", localeDate);
}

//方法二
+(NSString*)dateAsString:(NSDate*)date
{
    NSString *returntime = @"";
    NSDateFormatter *dateFormatter = nil;
    if (date != nil) {
        if (dateFormatter ==nil) {
            dateFormatter = [[NSDateFormatter alloc]init];
        }
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
        [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
        [dateFormatter setLocale:[NSLocale currentLocale]];
        returntime = [dateFormatter stringFromDate:date];
    }
    return returntime;
}
//方法三
+ (NSString *)fixStringForDate:(NSDate *)date
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *fixString = [dateFormatter stringFromDate:date];
    return fixString;
}

//方法四

    NSDateComponents *comps = [[NSDateComponentsalloc]init];
    [comps setYear:2010];
    [comps setMonth:8];
    [comps setDay:24];
    [comps setHour:17];
    [comps setMinute:5];
    [comps setTimeZone: [NSTimeZonetimeZoneWithAbbreviation:@"UTC"]];
    NSLog(@"%@", [NSTimeZonetimeZoneWithAbbreviation:@"UTC"]);
    
    NSCalendar *cal = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *referenceTime = [cal dateFromComponents:comps];
    NSLog(@"%@", referenceTime);



你可能感兴趣的:(ios)