9

I wanna set the system timezone, date time in iOS by code. Any ideas or private apis help me? Example: Set time zone to GMT+8, and date time to Aug 10, 2013 8:30 pm. How to do it? Thanks!

4

3 回答 3

21

正如其他人所说,您无法从应用程序中编辑系统时区,但是您可以+setDefaultTimeZone:使用on为整个应用程序设置默认时区NSTimeZone

你提到这是为了测试,所以我假设这是为了对一些自定义日期格式化程序等进行单元测试,在这种情况下你可以在你的单元测试中做这样的事情:

static NSTimeZone *cachedTimeZone;

@implementation DateUtilTests

+ (void)setUp
{
    [super setUp];
    cachedTimeZone = [NSTimeZone defaultTimeZone];
    // Set to whatever timezone you want your tests to run in
    [NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
}

+ (void)tearDown
{
    [NSTimeZone setDefaultTimeZone:cachedTimeZone];
    [super tearDown];
}

// ... do some tests ...

@end

我希望这会有所帮助!

于 2014-06-30T14:59:11.937 回答
3

仍在使用 Xcode 11。swift 5 实现如下所示:

override func setUpWithError() throws {
    // Put setup code here. This method is called before the invocation of each test method in the class.
    
    //All test by default will use GMT time zone. If different, change it within the func
    TimeZone.ReferenceType.default = gmtTimeZone
}

override func tearDownWithError() throws {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    
    //Rest to current
    TimeZone.ReferenceType.default = TimeZone.current
}

在我的 XCTestCase 类中,我的时区声明如下:

private let gmtTimeZone = TimeZone(abbreviation: "GMT")!
private let gmtPlus1TimeZone = TimeZone(abbreviation: "GMT+1")!
private let gmtMinus1TimeZone = TimeZone(abbreviation: "GMT-1")!

我将所有测试默认为 GMT,但对于特定测试,我想更改它,然后:

func test_Given_NotGMTTimeZone_ThenAssertToGMT() {
    TimeZone.ReferenceType.default = gmtPlus1TimeZone
    ...
}

已添加 您还可以使用时区名称,例如“英国夏令时间”

private let britishSummerTimeZone = TimeZone(abbreviation: "BST")!

添加

由于时区缓存,这对我不起作用。我需要在每次更改时区后重置缓存以阻止测试相互干扰。例如

TimeZone.ReferenceType.default = gmtTimeZone
TimeZone.ReferenceType.resetSystemTimeZone ()
于 2020-08-05T10:14:37.510 回答
2

@Filip 在评论中怎么说,无法在应用程序内编辑系统首选项。您可能会做的(不知道它是否对您有用)是在您的 APP 中设置您正在使用的 NSDates 的时区。

这是一个如何做到这一点的例子:

NSString *dateString = @"2013-08-07 17:49:54";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Europe/London"]; //set here the timezone you want
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:timeZone];

NSDate *date = [dateFormatter dateFromString:dateString];

这是与 timeZoneWithName 一起使用的可能时区列表:`:http ://pastebin.com/ibNU2RcG

于 2013-08-08T02:11:34.487 回答