mil*_*ari 10 iphone objective-c nsdate
我有一个关于NSDate的查询.我有一个日期,即"2011-10-04 07:36:38 +0000",我想检查这个日期是昨天,今天还是未来的日期.
我该怎么做?
Shr*_*hri 43
试试这个:
注意:根据需要更改日期格式.
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM/dd/yyyy"];
NSDate* enteredDate = [df dateFromString:@"10/04/2011"];
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:enteredDate];
switch (result)
{
case NSOrderedAscending:
NSLog(@"Future Date");
break;
case NSOrderedDescending:
NSLog(@"Earlier Date");
break;
case NSOrderedSame:
NSLog(@"Today/Null Date Passed"); //Not sure why This is case when null/wrong date is passed
break;
}
Run Code Online (Sandbox Code Playgroud)
NSDate *startDate = ...;
NSDate *endDate = ...;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
Run Code Online (Sandbox Code Playgroud)
如果days在+1和-1之间,则您的日期是"今天"的候选人.显然你需要考虑如何处理时间.据推测,最简单的方法是将所有日期设置为当天00:00.00小时(使用这样的方法截断日期),然后使用这些值进行计算.这样你今天得0,昨天得-1,明天+1,任何其他价值也会告诉你未来或过去的情况.
| 归档时间: |
|
| 查看次数: |
12783 次 |
| 最近记录: |