gpt4 book ai didi

iphone - 将 GMT 时间转换为本地时间

转载 作者:行者123 更新时间:2023-12-03 20:25:02 27 4
gpt4 key购买 nike

我使用以下代码在我的 iPhone 项目中获得了 GMT 格式的时间。但我想将其转换为本地时间。请提供一些解决此问题的想法。提前致谢。

NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];

NSString *resultString = [dateFormatter stringFromDate: currentTime];
[dateFormatter release];

我使用 GMT 格式将其发送到服务器。所以首先我只想要 GMT 格式。之后我想转换它。

最佳答案

使用此方法将当前时间转换为 GMT

    +(NSDate *)getCurrentGMTTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = -[tz secondsFromGMTForDate: [NSDate date]];
return [NSDate dateWithTimeInterval: seconds sinceDate: [NSDate date]];
}

然后使用该方法将GMT时间转换回本地时间。将您的 GMT NSDate 传递给此方法。

    +(NSDate *)getLocalTimeWithDate:(NSDate*)date
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: date];
return [NSDate dateWithTimeInterval:seconds sinceDate: date];
}

关于iphone - 将 GMT 时间转换为本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16435304/

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