Example of a comparison of the size of IOS time (Month day)

Source: Internet
Author: User
Tags comparison date1

Generally speaking of comparison size, we will think of comparing the size of two digits, but if you compare the size of two dates, such as: compare the size of 2016-07-21 and 2016-08-20, nsdate between the compare to achieve, collation method, the code is as follows:

-(void) Viewdidload {
[Super Viewdidload];
Do no additional setup after loading the view, typically from a nib.

NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[Dateformatter setdateformat:@ "Yyyy-mm-dd"];
NSDate *date1 = [dateformatter datefromstring:@ "2016-07-21"];
NSDate *date2 = [dateformatter datefromstring:@ "2016-08-20"];
if ([[NSString stringwithformat:@ "%d", [self compareoneday:date1 withanotherday:date2]] isequaltostring:@ "1"]) {
NSLog (@ "date1 > date2");
}else if ([[NSString stringwithformat:@ "%d", [self compareoneday:date1 withanotherday:date2]] isequaltostring:@ "-1"]) {
NSLog (@ "Date1 < Date2");
}else{
NSLog (@ "date1 = date2");
}
}

#pragma mark-time comparison size
-(int) Compareoneday: (NSDate *) oneday withanotherday: (nsdate *) anotherday
{
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[Dateformatter setdateformat:@ "dd-mm-yyyy"];
NSString *onedaystr = [Dateformatter stringfromdate:oneday];
NSString *anotherdaystr = [Dateformatter stringfromdate:anotherday];
NSDate *datea = [Dateformatter datefromstring:onedaystr];
NSDate *dateb = [Dateformatter datefromstring:anotherdaystr];
Nscomparisonresult result = [Datea compare:dateb];
NSLog (@ "oneday:%@, Anotherday:%@", Oneday, Anotherday);
if (result = = nsordereddescending) {
Oneday > Anotherday
return 1;
}
else if (result = = nsorderedascending) {
Oneday < Anotherday
return-1;
}
Oneday = Anotherday
return 0;
}
Print:
2016-08-20 09:41:04.061 comparedatetime[16742:676557] date1:2016-07-20 16:00:00 +0000, date2:2016-08-19 16:00:00 +0000
2016-08-20 09:41:04.062 comparedatetime[16742:676557] Date1 < Date2

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.