문제

I want to convert my Local date ([NSDate date]) to GMT to create a JSON string (/Date(1324435876019-0000)/).

My code works fine when i set my clock to EST time zone when i change my timezone to PST my code still acts as EST. Can you please tell me what is the problem is following code?

        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]];
도움이 되었습니까?

해결책

You can get the epoch GMT time by simply calling timeIntervalSince1970.

NSString *time = [NSString stringWithFormat:@"/Date(%lld-0000)/", 
                     (long long)([[NSDate date] timeIntervalSince1970] * 1000)];

다른 팁

@joe and @tommy you are right. Even i implemneted the same way as you mentioned. Problem was in server database. I found a hack. I just need to add 18000 (5 hr) second to the current local date and i am good. So code is

        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]];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top