3

我想将我的本地日期 ([NSDate date]) 转换为 GMT 以创建 JSON 字符串 (/Date(1324435876019-0000)/)。

当我将时钟设置为 EST 时区时,我的代码工作正常,而当我将时区更改为 PST 时,我的代码仍然充当 EST。你能告诉我下面的代码有什么问题吗?

        NSDate *localDate = [NSDate date];
    NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method
    NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
    NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];
    NSString *time = [NSString stringWithFormat:@"/Date(%@-0000)/", [NSNumber numberWithLongLong:[gmtDate timeIntervalSince1970] * 1000]];
4

2 回答 2

7

GMT您可以通过简单地调用来获取纪元时间timeIntervalSince1970

NSString *time = [NSString stringWithFormat:@"/Date(%lld-0000)/", 
                     (long long)([[NSDate date] timeIntervalSince1970] * 1000)];
于 2011-12-20T22:19:33.823 回答
0

@joe 和 @tommy 你是对的。即使我实施了与您提到的相同的方式。问题出在服务器数据库中。我发现了一个黑客。我只需要在当前本地日期加上 18000(5 小时)秒,我很好。所以代码是

        NSDate *localDate = [NSDate date];
    NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] + 18000;
    NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];

    NSString *time = [NSString stringWithFormat:@"/Date(%@-0000)/", [NSNumber numberWithLongLong:[gmtDate timeIntervalSince1970] * 1000]];
于 2011-12-21T21:52:08.110 回答