我希望将用户的时区设置为格式为UTC+5:30
我试过这样。
NSTimeZone *timeZone=[NSTimeZone localTimeZone];
NSLog(@"%@ || %@",timeZone.abbreviation,timeZone.name);
这给了我这个输出。 (但没有得到我想要的时间)
IST ||亚洲/加尔各答
由于
答案 0 :(得分:2)
您可以使用NSDate Formatter来获取UTC的偏移量:
NSDateFormatter *dates = [[NSDateFormatter alloc]init];
[dates setDateFormat:@"Z"];
NSLog(@"%@", [dates stringFromDate:[NSDate date]]);
这将记录:+0530(+5:30)
如果您想要它的特定格式,您可以这样做:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"Z"];
NSString *offetString = [dateFormatter stringFromDate:[NSDate date]];
NSString *formattedString = [NSString stringWithFormat:@"UTC%@:%@",[offetString substringWithRange:NSMakeRange(0, 3)],[offetString substringWithRange:NSMakeRange([offetString length] - 2, 2)]];
答案 1 :(得分:1)
NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.timeZone = [NSTimeZone localTimeZone];
df.dateFormat = @"Z";
NSString *localTimeZoneOffset = [df stringFromDate:[NSDate date]];
NSLog(@"%@",localTimeZoneOffset);
您将获得类似
的输出 +0530
UTC+5:30
。
更新:(正如评论中所述)
尝试下面所需格式的代码,
NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.timeZone = [NSTimeZone localTimeZone];
df.dateFormat = @"Z";
NSString *localTimeZoneOffset = [df stringFromDate:[NSDate date]];
NSLog(@"%@",localTimeZoneOffset);
NSString *one = [localTimeZoneOffset substringToIndex:1];
NSString *two = [localTimeZoneOffset substringWithRange:NSMakeRange(1, 2)];
NSString *three = [localTimeZoneOffset substringWithRange:NSMakeRange(3, 2)];
NSString *result = [NSString stringWithFormat:@"utc%@%@:%@",one,two,three];
NSLog(@"result : %@",result);