设置默认时区不成功

时间:2013-08-14 06:02:45

标签: ios objective-c cocoa-touch uitableview nsdate

我使用setDefaultTimezone设置时区并在UITableview中显示时间和地点。 enter image description here

我使用下面的代码来设置默认时区

[cell.detailTextLabel setText:[NSString stringWithFormat:@"%@", evnt.location]];
[NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithName:evnt.location]];
[cell.textLabel setText:[NSString stringWithFormat:@"%@",[NSDate date]]];

我必须做什么?

2 个答案:

答案 0 :(得分:1)

使用NSCalendar和setTimeZone方法。

  NSDate *newDate;
  NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:~              NSTimeZoneCalendarUnit fromDate:[NSDate date]];

  newDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
  NSLog(@"newDate: %@", newDate);
  NSLog(@"newDate: %.0f", [newDate timeIntervalSinceReferenceDate]);

newDate:2011-09-09 15:02:09 +0000 newDate:337273330

  [dateComponents setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Sydney"]];
  newDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
  NSLog(@"newDate: %@", newDate);
  NSLog(@"newDate: %.0f", [newDate timeIntervalSinceReferenceDate]);

newDate:2011-09-09 00:52:03 +0000 newTimeInterval:337222930

 [dateComponents setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Paris"]];
 newDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
 NSLog(@"newDate: %@", newDate);
 NSLog(@"newDate: %.0f", [newDate timeIntervalSinceReferenceDate]);

newDate:2011-09-09 08:52:03 +0000 newTimeInterval:337251730

答案 1 :(得分:0)

-[NSDate description]始终以UTC格式打印日期。

所以试着这样做:

NSDate *myDate = [[NSDate date] descriptionWithLocale:[NSLocale systemLocale]];

另外请查看以下内容:

NSDate is not returning my local Time zone /default time zone of device

https://stackoverflow.com/questions/13260787/setdefaulttimezone-not-working

Convert UTC NSDate to local Timezone Objective-C