【问题标题】:get Timezone in format of UTC+5:30获取 UTC+5:30 格式的时区
【发布时间】:2016-12-14 03:35:24
【问题描述】:

我想获取格式为 UTC+5:30 的字符串中的用户时区

我尝试过这样。

NSTimeZone *timeZone=[NSTimeZone localTimeZone];
NSLog(@"%@   ||   %@",timeZone.abbreviation,timeZone.name);

这给了我这个输出。 (但没有得到我想要的时间)

IST ||亚洲/加尔各答

谢谢

【问题讨论】:

  • 您期望的答案是什么,例如 +5.30 或 UTC+5:30
  • UTC+5:30 会更好

标签: ios objective-c timezone utc


【解决方案1】:
NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.timeZone = [NSTimeZone localTimeZone];
df.dateFormat = @"Z";
NSString *localTimeZoneOffset = [df stringFromDate:[NSDate date]];
NSLog(@"%@",localTimeZoneOffset);

你会得到类似的输出,

+0530UTC+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);

【讨论】:

    【解决方案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)]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-19
      • 2018-04-22
      • 2012-10-29
      • 2020-12-29
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      • 2015-01-10
      相关资源
      最近更新 更多