在我的iPhone应用程序中,我非常努力地将Web服务响应时间转换为当前设备时间。的webservice time in UTC-5 timezone。该应用程序是全球使用的应用程序。所以我必须将响应时间转换为当前设备的时区。这是简单的消息传递应用程序。
webservice time in UTC-5 timezone
当我发送了一个message the time is "5:05 PM" (India Chennai timezone)但从我那里检索时间 时webservice is "2012-07-16 07:33:01"。当我在应用程序中显示时间时,我应该将时间转换为设备的本地时间。我已经尝试过某种方式,但是我还不能解决。代码是:
message the time is "5:05 PM" (India Chennai timezone)
webservice is "2012-07-16 07:33:01"
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; [dateFormatter1 setLocale:[NSLocale currentLocale]]; //[dateFormatter1 setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]]; [dateFormatters setTimeZone:[NSTimeZone systemTimeZone]]; NSDate *date = [dateFormatter1 dateFromString:dateStr]; NSLog(@"date : %@",date);
但是输出日期和时间是2012-07-16 02:03:01 +0000我将这个日期/时间存储在其中Coredata,当我从下面的代码中检索CoreData并秘密NSString使用时,
2012-07-16 02:03:01 +0000
Coredata
CoreData
NSString
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init]; [dateFormatters setDateFormat:@"dd-MMM-yyyy hh:mm"]; [dateFormatters setDateStyle:NSDateFormatterShortStyle]; [dateFormatters setTimeStyle:NSDateFormatterShortStyle]; [dateFormatters setDoesRelativeDateFormatting:YES]; [dateFormatters setTimeZone:[NSTimeZone systemTimeZone]]; dateStr = [dateFormatters stringFromDate:dateString]; NSLog(@"DateString : %@", dateStr);
输出日期和时间为“ Today 7:33 AM”。它应该显示为“ Today 5:05 PM”。谁能救我一命?请帮助解决此问题。提前致谢。
Today 7:33 AM
Today 5:05 PM
我已经测试了您的方案并添加了一些代码供您参考。请测试以下内容,并让我知道它对您有用。
NSString *dateStr = @"2012-07-16 07:33:01"; NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *date = [dateFormatter1 dateFromString:dateStr]; NSLog(@"date : %@",date); NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone]; NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date]; NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date]; NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset; NSDate *destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date] autorelease]; NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init]; [dateFormatters setDateFormat:@"dd-MMM-yyyy hh:mm"]; [dateFormatters setDateStyle:NSDateFormatterShortStyle]; [dateFormatters setTimeStyle:NSDateFormatterShortStyle]; [dateFormatters setDoesRelativeDateFormatting:YES]; [dateFormatters setTimeZone:[NSTimeZone systemTimeZone]]; dateStr = [dateFormatters stringFromDate: destinationDate]; NSLog(@"DateString : %@", dateStr);
谢谢。