开发者

Date/time conversion to user's local time - issue

开发者 https://www.devze.com 2023-03-30 15:47 出处:网络
My application grabs a date / time from a remote server which is alway in GMT +1 (UTC/GMT +1 hour) timezone.

My application grabs a date / time from a remote server which is alway in GMT +1 (UTC/GMT +1 hour) timezone.

The format the server is providing is :

24 08 2011 08:45PM

I would like to convert this time stamp into the equivalent time/date of the users time zone (the user can be anywhere in the world).

thus as an example : 24 08 2011 08:45PM coming from the server should be presented

24 08 2011 09:45PM to an Italian user (rome) (GMT + 1)

This code works on some timezones but i have a bad feeling that there is something very wrong about it and that there is a much more elegant way to do it

NSString *dateString = @"24 08 2011 09:45PM";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setDat开发者_如何学GoeFormat:@"dd MM yyyy hh:mma"];
    NSDate *dateFromString = [[[NSDate alloc] init] autorelease];
    dateFromString = [dateFormatter dateFromString:dateString];


    NSDate* sourceDate = dateFromString;
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;
    NSString *thePubDate =  [dateFormatter stringFromDate:destinationDate];//[appLogic getPubDate];
    NSLog(@"Result : %@",thePubDate);
    [dateFormatter release];
    //[dateFromString release];
    [destinationDate release];

I will appreciate your thoughts and suggestions on the matter


Just set the timeZone in the dateFormatter, This code is enough

NSString *dateString = @"24 08 2011 09:45PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"];
[dateFormatter setTimeZone:sourceTimeZone];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];

The dateFromString will now have the date 24 08 2011 08:45PM(GMT).. Then to convert this to string with local time just code the following,

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"];
NSString *stringFromDAte = [dateFormatter stringFromDate:dateString];
0

精彩评论

暂无评论...
验证码 换一张
取 消