1

我试图从 NSDate 获取本地时间,它只输出 +0000 时区。我正在解析 ICS 文件中的信息,然后使用 NSDateFormatter 将字符串(看起来像 20131001T114445Z)转换为日期,但由于某种原因,我无法将其更改为用户的本地时间。

这是相关代码 -

+(ISParseICS*) icsParser
{
    if( !fetcher ) {
        fetcher = [ISParseICS new];
        fetcher.dateFormatter = [[NSDateFormatter alloc] init];
        [fetcher.dateFormatter setDateFormat:@"yyyyMMdd HHmmss"];

        NSLog(@"Created new singleton fetcher");
    }
    return fetcher;
}

-(NSMutableArray *)fetchPassesSync 中的以下代码

// Extract date/time
        NSString *unformattedEndDateTimeString;
        NSDate *endDate;
        eventScanner = [NSScanner scannerWithString:event];
        [eventScanner scanUpToString:@"DTEND:" intoString:nil];
        [eventScanner scanUpToString:@"\n" intoString:&unformattedEndDateTimeString];

        unformattedEndDateTimeString = [unformattedEndDateTimeString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"DTEND:"] withString:@""];
        NSLog(@"This is unformattedEndDateTimeString: %@", unformattedEndDateTimeString);
        endDate = [self dateFromString:unformattedEndDateTimeString];
        NSLog(@"End date - %@", endDate);

......最后一块:

-(NSDate *)dateFromString:(NSString *)dateString {

    dateString = [dateString stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    dateString = [dateString stringByReplacingOccurrencesOfString:@"Z" withString:@""];
    NSDate *date = [self.dateFormatter dateFromString:dateString];


//    NSLog(@"The output date: %@", date);


    return date;
}

我对编程很陌生,我希望我正确地提出了这个问题。提前致谢。

编辑:我从所有这些代码中得到的是它采用字符串“20131001T114445Z”并像这样输出“2013-10-01 11:44:45 +0000”

4

1 回答 1

1

试试这个:-

 NSString *dateStr = @"20131001T114445Z";

    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    [dateFormat setDateFormat:@"yyyyMMdd'T'hhmmss'Z'"];
    NSDate *date = [dateFormat dateFromString:dateStr];

    // Convert date object to desired output format
    [dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
    dateStr = [dateFormat stringFromDate:date];
    NSLog(@"%@",dateStr);
    [dateFormat release];
于 2013-10-03T07:14:36.747 回答