-1

我有一个字符串2013-03-05T07:37:26.853,我想得到Output : 2013-03-05 07:37:26. 我想要对象的最终输出NSDate。我正在使用以下函数来转换欲望输出。它返回错误的时间。

-  (NSDate *) getDateFromCustomString:(NSString *) dateStr 
{    NSArray *dateStrParts = [dateStr componentsSeparatedByString:@"T"];
    NSString *datePart = [dateStrParts objectAtIndex:0];
    NSString *timePart = [dateStrParts objectAtIndex:1];
    NSArray *dateParts = [datePart componentsSeparatedByString:@"-"];
    NSArray *timeParts = [timePart componentsSeparatedByString:@":"];

NSDateComponents *components = [[NSDateComponents alloc] init];

[components setHour:[[timeParts objectAtIndex:0] intValue]];
[components setMinute:[[timeParts objectAtIndex:1] intValue]];
[components setSecond:[[timeParts objectAtIndex:2] intValue]];

[components setYear:[[dateParts objectAtIndex:0] intValue]];
[components setMonth:[[dateParts objectAtIndex:1] intValue]];
[components setDay:[[dateParts objectAtIndex:2] intValue]];


NSCalendar *currentCalendar = [NSCalendar currentCalendar];  
NSDate *date = [currentCalendar dateFromComponents:components];
NSLog(@"Date 1:%@",date); // Returns wrong time (2013-03-05 02:07:26)

/* i had tried the below.
NSDateFormatter * format = [[NSDateFormatter alloc] init];
[format setTimeZone:NSTimeZoneNameStyleStandard];
[format setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

NSLog(@"Date 2:%@",[format stringFromDate:date]); // Returns correct date (2013-03-05 07:37:26)

NSDate *fDate = [format dateFromString:[format stringFromDate:date]];
DLog(@"Date 3:%@",fDate); // Returns wrong time (2013-03-05 02:07:26)
*/

[components release];
return  date;
}

如果有任何想法,请建议我。

4

3 回答 3

2

您在这里看到的是时区问题。如果你想 NSLog 一个正确的日期,我们需要给输入字符串一个 GMT 时区:

将此添加到您的代码中,看看会发生什么:

[components setTimeZone: [NSTimeZone timeZoneForSecondsFromGMT: 0]];
于 2013-03-09T06:26:44.700 回答
1

尝试这个,

    NSString *departTimeDate = @"2013-03-05T07:37:26.853";

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS"];

    NSDate *date = [dateFormatter dateFromString:departTimeDate];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSLog(@"Expected Result___ %@",[dateFormatter stringFromDate:date]); //2013-03-05 07:37:26
于 2013-03-09T06:34:17.970 回答
0

试试这个:问题是时区。

+ (NSDate *) getDate:(NSString *) dateStr
{
    NSArray *dateStrParts = [dateStr componentsSeparatedByString:@"T"];
    NSString *datePart = [dateStrParts objectAtIndex:0];
    NSString *timePart = [dateStrParts objectAtIndex:1];

    NSString *t = [[timePart componentsSeparatedByString:@"."] objectAtIndex:0];
    NSString *newDateStr = [NSString stringWithFormat:@"%@ %@",datePart,t];
    //2013-03-05 07:37:26

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [df dateFromString:newDateStr];
    DLog(@"%@",date);

    return  date;
}
于 2013-03-09T09:47:49.083 回答