Iphone 将选择器中的日期与当前日期进行比较
在我的日期选择器中,我可以从列表中选择一个日期 我将其保存在字符串pickUpDateTime中Iphone 将选择器中的日期与当前日期进行比较,iphone,objective-c,Iphone,Objective C,在我的日期选择器中,我可以从列表中选择一个日期 我将其保存在字符串pickUpDateTime中 self.pickUpDateTime = [NSString stringWithString:[apiFormat stringFromDate:d]]; 我遇到了一个问题,用户可以选择过去的日期。有什么方法可以得到当前的一天,并检查它是否在未来 我的字符串保存的日期如下2010-11-04。 用户不能选择过去或当前的日期 谢谢 -代码您可以通过以下方式获取当前日期和时间: NSDate *
self.pickUpDateTime = [NSString stringWithString:[apiFormat stringFromDate:d]];
我遇到了一个问题,用户可以选择过去的日期。有什么方法可以得到当前的一天,并检查它是否在未来
我的字符串保存的日期如下2010-11-04。
用户不能选择过去或当前的日期
谢谢
-代码您可以通过以下方式获取当前日期和时间:
NSDate *now = [NSDate date];
将这两个日期与以下日期进行比较:
if ([d compare:now] == NSOrderedDescending) {
// d is later than now
} else {
// d is earlier than or equal to now
}
如果您使用的是
UIDatePicker
,只需设置
datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:24*3600];
e、 允许日期从明天开始。从日期字符串“2010-11-04”回溯到
NSDate
对象是可能的,但很麻烦。(但如果您坚持,请查看一下NSDateFormatter
)上面的许多答案都提供了有关使用NSDates的良好建议;如果你想在一天开始的时候说“至少明天”,而不是“至少24小时后”,事情就有点复杂了
一般而言:
- NSCalendar+currentCalendar或-initWithCalendarIdentifier:NSGregorianCalendar是额外安全的
- NSCalendar-components:fromDate:(第一个参数是一个标志字段,指示需要填写日期的哪些位)和-dateFromComponents:
- NSDate-时间间隔起始日期:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
NSString *tempStr=[NSString stringWithFormat:@"%@",[df stringFromDate:datePicker.date]];
txtBirth.text=tempStr;
NSString *birthDate = tempStr;
NSDate *todayDate = [NSDate date];
int time = [todayDate timeIntervalSinceDate:[df dateFromString:birthDate]];
int numberOfDays = time/86400;