将GMT时间转换为当地时间
我现在得到GMT时间 – 2013-05-15 08:55 AM
我目前的当地时间是 – 2013-05-15 02:06 PM和时区是 – 亚洲/加尔各答
我试图用上面的代码把上面的GMT转换成我的本地时间
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"Asia/Kolkata"]; [dateFormatter setTimeZone:sourceTimeZone]; // timeStamp - is the above GMT time NSDate *dateFromString = [dateFormatter dateFromString:timeStamp]; NSLog(@"local time is %@",dateFromString);
但是这给我这个时间 – 2013-05-14 19:04:00 +0000而不是2013-05-14 02:06 PM
为什么会发生? 请帮我明确这一点。提前感谢
没有什么是错误的,一个NSDate
实例将永远不会有一个时区(好吧,但它总是格林尼治标准时间,由date描述+0000
时区表示)。
你在代码中告诉dateformatter的是,你想parsing的date的时区是Asia/Kolkata
但你希望它是GMT
。
首先,您需要根据input的datestring制作一个NSDate
对象,将时区设置为您所指定的正确时区GMT
。
NSTimeZone *gmtTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; [dateFormatter setTimeZone:sourceTimeZone]; NSDate *dateFromString = [dateFormatter dateFromString:timeStamp]; NSLog(@"Input date as GMT: %@",dateFromString);
那么当你把date作为一个string使用时:
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Kolkata"]; [dateFormatter setTimeZone:sourceTimeZone]; NSString *dateRepresentation = [dateFormatter stringFromDate:dateFromString]; NSLog(@"Date formated with local time zone: %@",dateRepresentation);
我发现将GMT时间转换为当地时区的最短途径是
NSDate* localDateTime = [NSDate dateWithTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT] sinceDate:dateInGMT];
此外,将此date值转换为string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"HH:mm:ss"];//use the formatted as per your requirement. //Optionally for time zone converstions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *localTimeDateString = [formatter stringFromDate:localDateTime];
NSLog(@"local time is %@",[dateFormatter stringFromDate: dateFromString]);
NSTimeZone* gmtTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; NSTimeZone* localTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"Asia/Kolkata"]; NSDateFormatter *gmtDateFormatter = [[NSDateFormatter alloc] init]; [gmtDateFormatter setTimeZone:gmtTimeZone]; NSDate *date = [gmtDateFormatter dateFromString:timestamp]; NSDateFormatter *localDateFormatter = [[NSDateFormatter alloc] init]; [localDateFormatter setTimeZone:localTimeZone]; NSLog(@"local time is %@",[localDateFormatter stringFromDate:date]);
使用timeZoneWithName
NSDate *date=[[NSDate alloc]init]; NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init]; [timeFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Kolkata"]]; [timeFormat setDateFormat:@"HH:mm"]; NSString *dateStr=[timeFormat stringFromDate:date];