gpt4 book ai didi

iOS 将服务器时间转换为设备本地时间?

转载 作者:行者123 更新时间:2023-11-29 01:37:21 25 4
gpt4 key购买 nike

我在将服务器时间(阿根廷)转换为设备本地时间时遇到了一些问题。这是我当前的代码-

    -(NSString *)getLocalTimeStringFrom:(NSString *)sourceTime
{
static NSDateFormatter* df = nil;
if (df == nil)
{
df = [[NSDateFormatter alloc]init];
}
df.dateFormat = @"HH:mm:ss";

NSDate* d = [df dateFromString:sourceTime];
NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:@"ART"];//America/Argentina/Buenos_Aires (GMT-3)
NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone]; //Asia/Kolkata (IST)

[df setTimeZone: sourceZone];
NSLog(@"sourceZone time is %@" , [df stringFromDate: d]);
[df setTimeZone: localTimeZone];
NSLog(@"local time is %@" , [df stringFromDate: d]);

NSLog(@"original time string was %@" , sourceTime);
return [df stringFromDate: d];
}

如果 sourceTime 字符串是 00:05:00

,这里是日志
    2015-09-28 15:04:24.118 DeviceP[230:17733] sourceZone time is 15:35:00
2015-09-28 15:04:24.121 DeviceP[230:17733] local time is 00:05:00
2015-09-28 15:04:33.029 DeviceP[230:17733] original time string was 00:05:00

请注意,我得到的本地时间与我传递给该方法的时间字符串相同。我查看了各种 SO 帖子,例如 thisthis .任何帮助将不胜感激。

最佳答案

由于您的时间字符串在 ART 中,因此您应该在从字符串生成日期之前设置日期格式化程序的时区。表示喜欢关注

-(NSString *)getLocalTimeStringFrom:(NSString *)sourceTime
{
static NSDateFormatter* df = nil;
if (!df) {
df = [[NSDateFormatter alloc]init];
df.dateFormat = @"HH:mm:ss";
}

NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:@"ART"];
[df setTimeZone: sourceZone];
NSDate *ds = [df dateFromString:sourceTime];
NSLog(@"sourceZone time is %@" , [df stringFromDate: ds]);

NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
[df setTimeZone: localTimeZone];
NSLog(@"local time is %@" , [df stringFromDate: ds]);

return [df stringFromDate: d];
}

关于iOS 将服务器时间转换为设备本地时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32819436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com