NSDateComponents 中的 NSDate 问题 [英] Issue with NSDate from NSDateComponents

查看:42
本文介绍了NSDateComponents 中的 NSDate 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have a string like 2013-03-05T07:37:26.853 and i want to get the Output : 2013-03-05 07:37:26. I want the final output in NSDate object. i am using below function to convert desire output. and it returning wrong time.

-  (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;
}

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

Plz suggest me if any idea.

推荐答案

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

What you're seeing here is a time zone issue. If you want to NSLog a correct looking date, we'll need to give the input string a GMT time zone:

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

Add this in your code and see what happens:

[components setTimeZone: [NSTimeZone timeZoneForSecondsFromGMT: 0]];

这篇关于NSDateComponents 中的 NSDate 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆