从字符串创建日期

时间:2011-01-19 18:58:15

标签: iphone objective-c ios4 ios-simulator

我无法从字符串中获取今天的时间。我是在UITextField的一段时间内阅读的,但日期是作为纪元的开始而出现

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH-mm"];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setLenient:YES];

NSLog(@"Format: %@",[formatter dateFormat]);    
NSDate *now = [formatter dateFromString:[textbox text]];
NSLog(@"Time from textfield: %@",now]);

这从日志代码中提供以下日期。

2011-01-19 18:56:28.193 MyApp[8284:207] The time for now: 1970-01-01 06:00:00 GMT

2 个答案:

答案 0 :(得分:1)

为格式化程序设置dateStyletimeStyle将覆盖您手动设置的dateFormat。以下内容应按预期工作:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH-mm"];
[formatter setLenient:YES];

NSLog(@"Format: %@",[formatter dateFormat]);

[formatter release];

生成的日期对象将接近纪元的开头,因为您没有提供年,月和日。如果您希望文本字段中的时间代表今天日期的时间,则必须添加一些额外的代码:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH-mm"];
[formatter setLenient:YES];
NSDate *time = [formatter dateFromString:[textbox text]];
[formatter release];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:NSYearCalendarUnit |
                                               NSMonthCalendarUnit |
                                               NSDayCalendarUnit |
                                               NSHourCalendarUnit |
                                               NSMinuteCalendarUnit
                                      fromDate:[NSDate date]];
NSDateComponents *timeComps = [calendar components:NSHourCalendarUnit |
                                                   NSMinuteCalendarUnit
                                          fromDate:time];

[comps setHour:[timeComps hour]];
[comps setMinute:[timeComps minute]];
NSDate *date = [calendar dateFromComponents:comps];
NSLog(@"Date from textfield: %@",date);

答案 1 :(得分:0)

NSDate *todayDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:todayDate];
NSLog(@"The current time is:%@",currentTime);
[dateFormatter release];