Вопрос

«31-DEC-2010 9:00 до 13:00 вечера»

Например, примите вышеуказанные NSString, мне нужно преобразовать его до 2 NSDates, например, 31-декабрь-2010, 9:00 утра и 31 декабря 2010 года. 13:00.

Затем сравните его с текущей датой, чтобы увидеть, попадет ли текущая дата в данные даты.

Таким образом, 31-декабрь-2010 10:00 утра влюбился бы внутри.

Мне интересно, каковы лучшие практики / трюки с целью с целью сделать это элегантно?

Это было полезно?

Решение

Как получается, NSDateFormatter имеет метод свидания, который имеет именно то, что вы хотите.

http://blog.evandavey.com/2008/12/how-to-convert-a-string-To-nsdate.html.

Официальная документация для NSDateFormatter:

http://developer.apple.com/library/mac/#documentation/cocoa /reference/foundation/Classes/nsdateformatter_class/reference/reference.html.

Другие советы

Я закончил делать это так:

    NSString *temp = [[dateString allValues] objectAtIndex:0];

    NSLog(@"temp: %@", temp);


    NSArray *tokens = [temp componentsSeparatedByString: @" "];


    NSArray *tokenOneDelimited =  [[tokens objectAtIndex:0] componentsSeparatedByString: @"-"];


    NSString *dateStr1 = [NSString stringWithFormat: @"%@-%@-%@ %@",    [tokenOneDelimited  objectAtIndex:2],
                                                                        [tokenOneDelimited  objectAtIndex:1],
                                                                        [tokenOneDelimited  objectAtIndex:0],
                                                                        [tokens             objectAtIndex:1]];

    NSString *dateStr2 = [NSString stringWithFormat: @"%@-%@-%@ %@",    [tokenOneDelimited  objectAtIndex:2],
                          [tokenOneDelimited    objectAtIndex:1],
                          [tokenOneDelimited    objectAtIndex:0],
                          [tokens               objectAtIndex:3]];

    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

    [dateFormatter setDateFormat:@"yyyy-MMM-dd hh:mma"];

    NSDate *myDate1 = [dateFormatter dateFromString: dateStr1];

    NSDate *myDate2 = [dateFormatter dateFromString: dateStr2];

    NSDate *currentDate = [NSDate date];

    NSComparisonResult comparison = [currentDate compare: myDate1];

    NSComparisonResult comparison2 = [currentDate compare: myDate2];


    if ( 
        comparison      == NSOrderedDescending &&
        comparison2     == NSOrderedAscending
        )
    {
        NSLog(@"is On now");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top