IOS-string converted to NSDate type, difference between calculation and current time, number of months, number of days

Source: Internet
Author: User

NSString * dateStr = [dic objectForKey: @ "date"]; // 2012-05-17 11:23:23
NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateFormatter * format = [[NSDateFormatter alloc] init];
[Format setDateFormat: @ "yyyy-MM-dd HH: mm: ss"];
NSDate * fromdate = [format dateFromString: dateStr];
NSTimeZone * fromzone = [NSTimeZone systemTimeZone];
NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
NSDate * fromDate = [fromdate dateByAddingTimeInterval: frominterval];
NSLog (@ "fromdate = % @", fromDate );
[Format release];
NSDate * date = [NSDate date];
NSTimeZone * zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate * localeDate = [date dateByAddingTimeInterval: interval];
NSLog (@ "enddate = % @", localeDate );
NSDateComponents * components = [gregorian components: unitFlags fromDate: fromDate toDate: localeDate options: 0];
NSInteger months = [components month];
NSInteger days = [components day]; // year [components year]
NSLog (@ "month = % d", months );
NSLog (@ "days = % d", days );
[Gregorian release];
If (months = 0 & days = 0 ){
DateStr = [[dateStr substringFromIndex: 11] substringToIndex: 5];
Cell. textLabel. text = [NSString stringWithFormat: @ "today % @", dateStr]; // Today
} Else if (months = 0 & days = 1 ){
DateStr = [[dateStr substringFromIndex: 11] substringToIndex: 5];
Cell. textLabel. text = [NSString stringWithFormat: @ "Yesterday % @", dateStr]; // Yesterday
} Else {
DateStr = [dateStr substringToIndex: 10];
Cell. textLabel. text = dateStr;
}

 


From shijiucdy's column

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.