gpt4 book ai didi

iOS NSDate 获取时区特定日期?

转载 作者:行者123 更新时间:2023-11-28 17:51:28 26 4
gpt4 key购买 nike

我从 Web 服务获取 HH:mm:ss 格式的时间,它处于阿根廷 (GMT-3) 时区。我想将这个时间转换为完整日期 (dd-MM-yyyy HH:mm:ss),最后将其转换为设备本地时区的日期。这是我的代码

-(NSString *)getLocalTimeStringFrom:(NSString *)sourceTime
{
static NSDateFormatter* df = nil;
static NSDateFormatter* df1 = nil;

if (!df) {
df = [[NSDateFormatter alloc]init];
df.dateFormat = @"dd-MM-yyyy HH:mm:ss";

}
if (!df1) {

df1 = [[NSDateFormatter alloc]init];
df1.dateFormat = @"dd-MM-yyyy";
}
NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:@"ART"];
[df setTimeZone: sourceZone];
[df1 setTimeZone: sourceZone];

NSString *artDate = [df1 stringFromDate:[NSDate date]]; // get 29-09-2015
NSString* timeStamp = [artDate stringByAppendingString:[NSString stringWithFormat:@" %@",sourceTime]]; // get 29-09-2015 00:05:00, if sourceTime is 00:05:00
NSDate *art = [df dateFromString:timeStamp];
NSLog(@"ART date %@" , art);//ART date 2015-09-29 03:05:00 +0000

NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
[df setTimeZone: localTimeZone];
NSLog(@"Local date %@" , [df stringFromDate: art]);

return [df stringFromDate: ds];
}

问题是我在 art 中获取 UTC 日期(如代码中所注释),请注意 art 的值为 2015-09-29 03 :05:00 +0000 是 UTC,格式是 yyyy-MM-dd HH:mm:ss,但应该是 ART 和 dd -MM-yyyy HH:mm:ss。我尝试了一些来自网络的代码,但没有得到解决方案。这段代码有什么问题?

最佳答案

我用这个:

NSDateFormatter* serverDf = [[NSDateFormatter alloc] init];
[serverDf setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-3*60*60]];
[serverDf setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
NSDate* gmtDate = [serverDf dateFromString:timeStamp];
// DDLogVerbose(@"DateTime in GMT: %@", gmtDate);

NSDateFormatter* localDF = [[NSDateFormatter alloc] init];
[localDF setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
[localDF setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSString *localDate = [localDF stringFromDate:gmtDate];

关于iOS NSDate 获取时区特定日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32844006/

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