如何使用日期格式化程序并比较两个日期字符串

时间:2015-05-06 16:34:16

标签: nsdateformatter xcode6.3 ios8.3

hii每个人我都想比较两个日期并执行一些动作我被困在洞里试图尽我所能,但我知道我可能会遗漏某些东西或做错事任何帮助都会很友好。 在我的代码下面

-(void)dailyCalendarViewDidSelect:(NSDate *)date
{
    //You can do any logic after the view select the date
    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateStyle:NSDateFormatterMediumStyle];
    [dateformat setDateStyle:NSDateFormatterMediumStyle] ;
    
   datestring1= [dateformat stringFromDate:date]; // date value by current selected date from my cal view
   NSLog(@"%@",datestring1);//output May 5, 2015
 // NSLog(@"%@",date);//output 2015-05-05 15:56:32 +0000
    datestring2 = [dateformat stringFromDate:mydate];//already fetched value
    NSLog(@"%@",datestring2);// output May 5, 2015
  // NSLog(@"%@",mydate);// output 2015-05-05 08:47:16 +0000
    if (datestring1 == datestring2) {
        
        NSLog(@"good to go");//not able to get this value
        
        
    }
    
    /*//even i try this block too
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    mydate1 = [[NSDate alloc]init];
    mydate1 = [dateFormat dateFromString:datestring1];
    NSLog(@"%@",mydate1);//otpt null
    mydate2 = [[NSDate alloc]init];
    mydate2 = [dateFormat dateFromString:datestring2];
    NSLog(@"%@",mydate2);//otpt //null
   
    if (mydate1 == mydate2) {
        
        NSLog(@"good to go");//getting value without matching condition
      

    }
      */
    
    
   
}

请提前了解任何帮助将会有所帮助

1 个答案:

答案 0 :(得分:0)

对于比较两个日期,两个日期必须是相同的格式

if ([date1 compare:date2] == NSOrderedDescending) 
{
    NSLog(@"date1 is later than date2(greater than current date)");
} 
else if ([date1 compare:date2] == NSOrderedAscending)
{
    NSLog(@"date1 is earlier than date2 (less than current date)");    
} 
else 
{
    NSLog(@"dates are the same");  
}

或试试这个

if ([[date1 earlierDate:date2] isEqualToDate:date1])
{
    NSLog(@"date1 is earlier than date2 (less than current date)");
}
else if ([[date1 laterDate:date2] isEqualToDate:date1])
{
    NSLog(@"date1 is later than date2(greater than current date)");
}
else 
{
    NSLog(@"dates are the same");  
}