iOS NSDate获取timeZone特定日期?

时间:2015-09-29 12:26:34

标签: ios datetime nsdateformatter

我从网络服务获得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和d d-MM-yyyy HH:mm:ss。我从网上尝试了一些代码,但没有得到解决方案。这段代码有什么问题?

3 个答案:

答案 0 :(得分:0)

我用这个:

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];

答案 1 :(得分:0)

愿你只想要一个合成的NSString,而不是一个NSDate, 因为我认为NSDate会添加一个' + 0000'

答案 2 :(得分:-1)

Try this.
 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
 [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
 NSDate *date = [dateFormatter dateFromString:yourString];
 NSString *str = [dateFormatter stringFromDate:date];