Objective-c 根据某一个时区的时间获取特定时区的时间

//获取默认时区的时间字符串
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *nowStr = [formatter stringFromDate:[NSDate date]];
    NSLog(@"now time without setting TimeZone\n Default TimeZone: %@, Local Time %@",[formatter timeZone], nowStr);

    NSDate *nowGMT = [formatter dateFromString:nowStr];
    NSLog(@"当地时间->标准时间%@",nowGMT);
    NSLog(@"标准时间->当地时间%@",[formatter stringFromDate:nowGMT]);
 
      
    //获取特定时区的时间字符串
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/Adak"]];
    NSString *AmericanNow = [formatter stringFromDate:[NSDate date]];  
    NSLog(@"now time with certain timezone: %@ Local Time %@", [formatter timeZone], AmericanNow);
     
    NSDate *AmericanGMT = [formatter dateFromString:AmericanNow];
    NSLog(@"特定时区的时间->标准时间%@",AmericanGMT);
    NSLog(@"标准时间->特定时区的时间%@",[formatter stringFromDate:AmericanGMT]);
     [formatter release];



/* 将系统默认时间转换称某个特别时区的时间[color=darkred][/color][size=x-large][/size]
     Step1:获取系统默认时间的时间字符串
    
     */
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:SS"];
    NSString *defaultNowStr = [dateFormatter stringFromDate:[NSDate date]];
    NSLog(@"获取系统默认时间的时间字符串%@", defaultNowStr);
   
   
    /*
     Step2:获取标准时间
     */
    NSDate *dateGMT = [dateFormatter dateFromString:defaultNowStr];
    NSLog(@"获取标准时间%@",dateGMT);
   
    /*将标准时间转换称特定时区的时间
     */
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/Adak"]];
    NSString *localDateStr = [dateFormatter stringFromDate:dateGMT];
    NSLog(@"将标准时间转换称特定时区的时间%@",localDateStr);
  
    [dateFormatter release];

//将某个时区的特定时间转化称另一个时区的对应时间
/*
    该例子将时区Asia/Tokyo的2011-12-30 16:45:00转化为
    时区America/Adak的相应时间
*/
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter2 setDateFormat:@"yyyy-MM-dd HH:mm:SS"];
    NSString *fromTimeZone = [[NSString alloc] initWithString:@"Asia/Tokyo"];
    NSString *date_fromTimeZone = [[NSString alloc] initWithString:@"2011-12-30 16:45:00"];
   
    [dateFormatter2 setTimeZone:[NSTimeZone timeZoneWithName:fromTimeZone]];
    NSDate *dateOfGMT = [dateFormatter2 dateFromString:date_fromTimeZone];
    [fromTimeZone release];
    [date_fromTimeZone release];
   
    NSString *toTimeZone = [[NSString alloc] initWithString:@"America/Adak"];
    [dateFormatter2 setTimeZone:[NSTimeZone timeZoneWithName:toTimeZone]];
    NSString *dateStrDst = [dateFormatter2 stringFromDate:dateOfGMT];
    NSLog(@"dateStrDst %@", dateStrDst);
    [toTimeZone release];
   
   
     [dateFormatter2 release];

你可能感兴趣的:(Objective-C)