문제

Below is the string of time stamp which is returned by some server

dateFromServer = 2013-07-08 16:45:03Z

I am doing the following to convert it to an NSDate

     NSDateFormatter *format         =   [[NSDateFormatter alloc] init];
                        [format setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss'Z'"];


    NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];
    [format setTimeZone:destinationTimeZone];

   dateFromServer                  =   [dateFromServer stringByReplacingOccurrencesOfString:@"T" withString:@" "];

   NSDate      *oldTime            =   [format dateFromString:dateFromServer];

and I am getting

oldTime is 2013-07-08 20:45:03 +0000

It looks like +4 is added to the original time stamp

Why does it do that, and how do I avoid this situation?

도움이 되었습니까?

해결책 2

I personally do not know objective C but I do know the point of the problem. I'll try to guess along with the syntax.

When you receive 2013-07-08 16:45:03Z the Z means UTC, or GMT+/-0000.

You are parsing it as a local timezone, or GMT-0400.

You then reemit it as reconverted into UTC with a 4 hour overcompensation.

To fix this, change:

NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];

to

NSTimeZone *destinationTimeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

Honestly, I'm not sure if you need to do any wrapping for the 0 to act as an NSInteger but that's what you need.

You may have been intermittently missing this bug as a failure to determine time would have fallen back to the desired effect.

Out of curiosity, could someone comment as to whether my code is at least partially correct?

다른 팁

The NSDate object doesn't preserve the timezone. Instead, when printing the date (I assume through a NSLog(@"%@", oldTime);) it will use the current timezone. If your system is set to GMT (+0000) then it will print like that.

The date is still correct, and if you force it to print with the correct time zone it will be correct.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top