以“GMT 5:30”NSString格式从NSTimeZone获取系统时区

时间:2015-10-14 05:53:07

标签: objective-c nsstring nstimezone

我对目标C有点新意。 我试图以字符串格式获取系统时区。我的字符串中只需要“ GMT 5:30 ”。

_devTimezone = (NSString*)[NSTimeZone systemTimeZone];

3 个答案:

答案 0 :(得分:0)

您可以使用NSTimeZone方法secondsFromGMT获取NSInteger值的偏移量,然后使用NSString方法stringWithFormat格式化您希望的方式将整数值分成小时和分钟的基本算术。

示例代码:

- (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

答案 1 :(得分:0)

这样做。

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);

希望对你有所帮助。

答案 2 :(得分:-1)

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

NSString *myDate = [[NSDate date] descriptionWithLocale:[NSLocale systemLocale]];
myDate=[myDate substringWithRange:NSMakeRange(26, 9)];
NSLog(@"%@",myDate);

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

**** **** EDITED

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

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);

快乐编码.. :)

相关问题