1

「2010年12月31日午前9時から午後1時」

上記のNSStringを例にとると、2つのNSDateに変換する必要があります(例:2010年12月31日9:00AMおよび2010年12月31日1:00PM)。

次に、それを現在の日付と比較して、現在の日付が指定された日付内にあるかどうかを確認します。

したがって、2010年12月31日午前10時が範囲内になります。

これをエレガントに行うためのObjectiveCのベストプラクティス/トリックは何ですか?

4

2 に答える 2

2

実は、NSDateFormatterにはdateFromStringメソッドがあり、これはまさにあなたが望むことを実行します。

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

于 2011-01-05T23:51:08.507 に答える
0

私はそのようにそれをすることになった:

    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");
于 2011-01-06T02:36:44.047 に答える