簡體   English   中英

iOS NSDate獲取timeZone特定日期?

[英]iOS NSDate get timeZone specific date?

我正在從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和d d-MM-yyyy HH:mm:ss 我嘗試了一些來自net的代碼,但是沒有找到解決方案。 該代碼有什么問題?

我用這個:

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

可能您只想要一個有格式的NSString,而不是NSDate,因為我認為NSDate將添加一個'+0000'

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM