将NSDate拆分为日期和时间

时间:2012-12-01 13:55:53

标签: ios nsdate nsdateformatter

我正在尝试将从Web服务收到的NSDate拆分为两个不同的日期,以便为每天的部分填充tableView以查找事件。我认为执行后者最简单的方法是创建一个查找唯一日期的获取请求。

所以我尝试创建一个NSDate" day"但将时间组件设置为00:00。我想知道是否有更有效的方法来实现这一目标:

if (eventoItemList.count > 0) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

        NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
        [dayFormatter setDateFormat:@"yyyy-MM-dd"];

        for (GDataXMLElement *eventoItem in eventoItemList) {
            BOEvent *event = [[BOEvent alloc] init];
            NSString *idEventStr = [[[eventoItem elementsForName:@"id"] objectAtIndex:0] stringValue];                       
            NSString *name = [[[eventoItem elementsForName:@"titulo"] objectAtIndex:0] stringValue];
            NSString *type = [[[eventoItem elementsForName:@"tipo"] objectAtIndex:0] stringValue];
            NSString *descr = [[[eventoItem elementsForName:@"descripcion"] objectAtIndex:0] stringValue];
            NSString *address = [[[eventoItem elementsForName:@"direccion"] objectAtIndex:0] stringValue];
            NSDate *date = [dateFormatter dateFromString:[[[eventoItem elementsForName:@"fecha"] objectAtIndex:0] stringValue]];
            NSString *action =  [[[eventoItem elementsForName:@"accion"] objectAtIndex:0] stringValue];

            [event setIdEvent:[idEventStr integerValue]];
            [event setName:name];
            [event setType:type];
            [event setDesc:descr];
            [event setAddress:address];
            [event setAction:action];
            [event setDate:date];
            [event setDayDate:[dayFormatter dateFromString:[dayFormatter stringFromDate:date]]];
            [events addObject:event];
        }
    }

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

将NSDate拆分为两个NSDates 的示例代码(仅限日期,仅限时间)

     NSDate *date = [NSDate date];
    NSCalendar *gregorian = [NSCalendar currentCalendar];

    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:date];    
    NSDate *dateOnly = [gregorian dateFromComponents:comps];

    unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit |  NSDayCalendarUnit;
    comps = [gregorian components:unitFlags fromDate:date];    
    NSDate *timeOnly = [gregorian dateFromComponents:comps];

    NSLog(@"%@ = \n\tDate: %@ \n\tTime: %@", date, dateOnly, timeOnly);

在两个 NSStrings

中输出NSDate的示例代码
    NSDate *date = [NSDate date];

    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateStyle:NSDateFormatterFullStyle];
    [f setTimeStyle:NSDateFormatterNoStyle];
    NSString *dateOnly = [f stringFromDate:date];

    [f setTimeStyle:NSDateFormatterFullStyle];
    [f setDateStyle:NSDateFormatterNoStyle];
    NSString *timeOnly = [f stringFromDate:date];

    NSLog(@"%@ = \n\tDate: %@ \n\tTime: %@", date, dateOnly, timeOnly);