zoukankan      html  css  js  c++  java
  • [ios]字符串转化成NSDate类型 计算与当前时间的相差 月数 天数 【转】

    NSString *dateStr=[dic objectForKey:@"date"];// 2012-05-17 11:23:23

        NSCalendar *gregorian = [[NSCalendaralloc] initWithCalendarIdentifier:NSGregorianCalendar];  

         NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;  

        NSDateFormatter *format=[[NSDateFormatteralloc] 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 = [NSTimeZonesystemTimeZone];

        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];//年[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:@"今天 %@",dateStr];//今天 11:23

        }else if(months==0&&days==1){

            dateStr=[[dateStr substringFromIndex:11]substringToIndex:5];

            cell.textLabel.text=[NSString stringWithFormat:@"昨天 %@",dateStr];//昨天 11:23

        }else{

            dateStr=[dateStr substringToIndex:10];

            cell.textLabel.text=dateStr;

        }


  • 相关阅读:
    Web框架
    Java并发编程:Callable、Future和FutureTask
    5分钟了解Mockito
    用IntelliJ IDEA创建Gradle项目简单入门
    QrenCode : linux命令行下生成二维码图片
    git 撤销commit
    curl网站开发指南
    H2数据库攻略
    Guice入门
    linux debian 时间设置中无法选择“自动设定时间和日期”
  • 原文地址:https://www.cnblogs.com/jinjiantong/p/3013710.html
Copyright © 2011-2022 走看看