【问题标题】:How to convert my server time to other country time?如何将我的服务器时间转换为其他国家/地区时间?
【发布时间】:2016-11-21 20:59:23
【问题描述】:

我从服务器获取时间是2016/07/19--12:20:00 现在我必须根据国家/地区更改这个时间。 例如,如果我在奥克兰,那么时间必须喜欢2016/07/19--18:50:00 我在堆栈溢出中找到了很多解决方案,但我无法解决这个问题。 请帮帮我

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY/MM/dd--HH:mm:ss"];
        NSDate* sourceDate = [dateFormatter dateFromString:model.tripEndTime];
        NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
        NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
        NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
        NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
        NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
        NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
        [dateFormat setDateFormat:@"YYYY/MM/dd--HH:mm:ss"];
        NSString* localTime = [dateFormat stringFromDate:destinationDate];
        NSLog(@"localTime:%@", localTime);

我用这段代码试过

【问题讨论】:

  • 你能展示你尝试过的代码吗
  • 服务器的时间是GMT吗?

标签: ios objective-c timezone nsdate


【解决方案1】:

只需将服务器时间转换为 UTC 时间,然后再转换为当地国家时间。只需为此编写一个单独的方法

 +(NSString*)convertLocaleTimeToChatTimeStampWithDateStr:(NSString  *)strDate
{
NSDateFormatter *df = [DateHelper getDefaultTimeFormatter];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date = [df dateFromString:strDate];
[df setDateFormat:@"dd MMM, hh:mm a"];
[df setTimeZone:[NSTimeZone localTimeZone]];
return [df stringFromDate:date];
}

+(NSDateFormatter*)getDefaultTimeFormatter
{
NSDateFormatter *df = [NSDateFormatter new];
[df setDateStyle:NSDateFormatterNoStyle];
[df setTimeStyle:NSDateFormatterShortStyle];
return df;
}

希望这能解决您的问题。谢谢

【讨论】:

  • 我认为与其直接设置时区,不如使用手机的时区?唯一的问题是如果手机没有切换到当前时区
【解决方案2】:

最好使用服务器时间戳。获取时间戳后根据时区进行转换

【讨论】:

  • 你能举个例子@ios Developer
  • NSString * timestamp = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
  • 这是为了获取当前时间戳和获取服务器时间戳,你必须在服务器端编写代码
  • @iosDeveloper 你没有回答这个问题。我认为这个问题是有效的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 2019-05-29
  • 2021-03-20
  • 2015-11-22
  • 2014-08-25
  • 2010-09-24
相关资源
最近更新 更多