我的日期选择器返回错误的分钟和秒数值

时间:2013-04-03 10:32:17

标签: ios objective-c datepicker nsdate nsdateformatter

我的日期选择器返回错误的分钟和秒数值,但小时工作正常。这是我得到它的方法。

-(NSDate *)datePickerTime
{
NSCalendar *gregorianCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
[gregorianCalendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setDateFormat:@"HH:mm:ss"];
[format setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateString =[format stringFromDate:[self.timePicker date]];
NSDate *adjustedDate = [format dateFromString:dateString];
NSDateComponents *comp = [[NSDateComponents alloc]init];

comp = [gregorianCalendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:adjustedDate];

reminderTime = [gregorianCalendar dateFromComponents:comp];

return reminderTime;
}

2 个答案:

答案 0 :(得分:1)

请检查日期选择器的最佳Apple sample code,并提供所有格式支持!

您的问题可能在setDateFormat ISO-8601

试试这段代码

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"hh:mm:ss a"];

NSLog(@"Current Date: %@", [formatter stringFromDate:[NSDate date]]);

[formatter release];

答案 1 :(得分:0)

在我的应用程序中,我通过以下

获得正确的时间
NSDate *endDate = [NSDate date];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:@"HH:mm:ss"];
NSString* curdatestr = [dateFormatter2 stringFromDate:endDate];
NSLog(@"str%@",curdatestr);

如果您还希望使用当前时间的日期

[dateFormatter2 setDateFormat:@"yyyy-MM-dd 'at' HH:mm:ss"];