首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从NSTimeZone获取“格林尼治时间5:30”NSString格式的系统时区

从NSTimeZone获取“格林尼治时间5:30”NSString格式的系统时区
EN

Stack Overflow用户
提问于 2015-10-14 05:53:07
回答 3查看 995关注 0票数 1

我对目标C有点陌生。我正在尝试以字符串格式获取系统时区。我只需要“格林尼治时间5:30”在我的字符串。

代码语言:javascript
复制
_devTimezone = (NSString*)[NSTimeZone systemTimeZone];
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-10-14 06:41:24

您可以将日期描述作为字符串,然后将所需的子字符串作为

代码语言:javascript
复制
NSString *myDate = [[NSDate date] descriptionWithLocale:[NSLocale systemLocale]];
myDate=[myDate substringWithRange:NSMakeRange(26, 9)];
NSLog(@"%@",myDate);

你会在日志中得到GMT+05:30。

*编辑*

如果不确定什么是索引,可以设置日期格式,然后访问索引。

代码语言:javascript
复制
NSString *dateStr = @"Wed, 14 Oct 2015 12:53:58 +0000";

 // Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSString *myDate = [date descriptionWithLocale:[NSLocale systemLocale]];
myDate=[myDate substringWithRange:NSMakeRange(26, 9)]; 
NSLog(@"%@",myDate);

快乐编码..。:)

票数 -1
EN

Stack Overflow用户

发布于 2015-10-14 07:05:50

您可以使用NSTimeZone方法secondsFromGMT获取偏移量作为NSInteger值,然后使用NSString方法stringWithFormat和基本算法将整数值划分为小时和分钟来格式化您想要的格式。

样本代码:

代码语言:javascript
复制
- (NSString *) getTimeZoneOffset:(NSTimeZone *)timezone
{
   NSInteger minutesFromGMT = timezone.secondsFromGMT / 60; 

   // handle negative offsets
   char sign;
   if (minutesFromGMT < 0)
   {
      sign = '-';
      minutesFromGMT = -minutesFromGMT; // make positive
   }
   else
      sign = '+';

   // split in hours and minutes
   NSInteger hoursFromGMT = minutesFromGMT / 60;
   minutesFromGMT %= 60;

   // format as string - making sure minutes is two digits with leading zero if needed
   // cast to int is OK as no value will be greater than 59!
   return [NSString stringWithFormat:@"GMT%c%d:%02d", sign, (int)hoursFromGMT, (int)minutesFromGMT];
}

HTH

票数 0
EN

Stack Overflow用户

发布于 2015-10-14 07:41:10

就像这样。

代码语言:javascript
复制
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];

//set timezone to GMT 5:30.
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

NSString *currentTime = [dateFormatter stringFromDate:currentDate];
NSLog(@"User's current time %@",currentTime);

希望它能帮到你。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33117601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档