当我尝试从文本字段获取日期和时间值时,我在控制台上得到了错误的值。日期和时间是两个文本字段
NSString *datestring = self.date.text;
NSString *timestring = self.time.text;
NSString *combined = [NSString stringWithFormat:@"%@ %@",datestring,timestring];
NSLog(@"%@",combined);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd yyyy HH:mm:ss"];
NSDate *dates = [dateFormat dateFromString:combined];
NSLog(@"%@",dates);
最佳答案
不要依赖 NSDate
description
方法来为您提供所需的日期,它实际上只是用于调试。而是使用 NSDateFormatter
方法 stringFromDate:
。
NSString *combinedDateString = @"may 2 2000 02:00 AM";
NSLog(@"combinedDateString: %@", combinedDateString);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd yyyy hh:mm aa"];
NSDate *date = [dateFormat dateFromString:combinedDateString];
NSString *recoveredDateString = [dateFormat stringFromDate:date];
NSLog(@"recoveredDateString: %@", recoveredDateString);
NSLog 输出:
combinedDateString: may 2 2000 02:00 AM
recoveredDateString: May 02 2000 02:00 AM
根据需要选择不同的显示格式。
注意:“HH”表示 24 小时时间,“hh”表示 12 小时时间。
参见 ICU Formatting Dates and Times用于日期格式。
关于ios - 从 NSDateFormatter 获取错误的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23891422/