How to compare two dates in iphone?

后端 未结 6 1189
渐次进展
渐次进展 2020-12-22 09:50

I want to compare the todays date and other date coming from my database. For example, 2011-03-25 compare it with 2011-02-25

How can i formate my database date as t

相关标签:
6条回答
  • 2020-12-22 10:16

    Cocoa has couple of methods for this:

    in NSDate

    – isEqualToDate:
    – earlierDate:
    – laterDate:
    – compare:

    When you use - (NSComparisonResult)compare:(NSDate *)anotherDate ,you get back one of these:

    The receiver and anotherDate are exactly equal to each other, NSOrderedSame
    The receiver is later in time than anotherDate, NSOrderedDescending
    The receiver is earlier in time than anotherDate, NSOrderedAscending.
    

    for more read the SO post

    Just go through the blog post, there are many date related utility functions.

    http://arstechnica.com/apple/guides/2010/03/how-to-real-world-dates-with-the-iphone-sdk.ars/2

    0 讨论(0)
  • 2020-12-22 10:17

    http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtDates.html#//apple_ref/doc/uid/20000183-BCIDBADB

    Isn't that the same on Iphone?

    0 讨论(0)
  • 2020-12-22 10:24

    In Swift:

    let date1 = NSDate() //some date
    let date2 = NSDate() //another date
    
    let firstDate = date1.earlierDate(date2)
    let lastDate = date1.laterDate(date2)
    
    0 讨论(0)
  • 2020-12-22 10:30
    NSDate *date1 = [NSDate date];
    NSDate *date2 = [NSDate date];
    
    if ([date1 compare: date2]==NSOrderedAscending) {
        NSLog(@"YES");
    }
    
    0 讨论(0)
  • 2020-12-22 10:32

    If your date are string like year-month-day, you can just compare string:

     if ([date1 compare:string2]==NSOrderedAscending) {
     } else if ([date1 compare:string2]== NSOrderedDescending) {
     } else {
     }
    

    It will works because fields in date are from most important to less, like a string comparison.

    0 讨论(0)
  • 2020-12-22 10:38

    You can use NSDate compare: or timeIntervalSinceReferenceDate -- that'll get you started

    0 讨论(0)
提交回复
热议问题