2

これは本当に簡単なはずです!

私は店を持っています。8:30 に開店し、17:00 に閉店します。現在開いているお店または現在閉まっているお店をアプリに伝えたいです。

open_time と close_time を保存する最良の方法は何ですか? 1 日の開始からの秒数、つまり 30600 と 63000 として保存しますか?

これは理にかなっていますが、今日の開始からの秒数で現在の時刻を取得するにはどうすればよいので、 current_time が open_time と close_time の間にあるかどうか、つまり open!!

前もって感謝します!

4

3 に答える 3

2

この問題は、あなたが思っているほど簡単ではありません。日付は非常に慎重に扱う必要があります。最善の解決策は、すべての開店時間と閉店時間を日付として保存することです。開店時間と閉店時間を作成して比較するためのコードを次に示します。

NSDate * now = [NSDate date];
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents * comps = [calendar components:~(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
[comps setHour:8];
[comps setMinute:30];
NSDate * open = [calendar dateFromComponents:comps];
[comps setHour:17];
[comps setMinute:0];
NSDate * close = [calendar dateFromComponents:comps];

if ([now compare:open] == NSOrderedDescending && [now compare:close] == NSOrderedAscending) {
    // The date is within the shop's hours.
}
else {
    // The date is not within the shop's hours.
}

これが私がしたことです:

  1. 現在の日付を取得します。

  2. 時間、分、秒を除く、日付のコンポーネントを取得します。

  3. 時間と分を設定します。

  4. オープンタイムを作る。

  5. 閉店時間までステップ 3 ~ 4 を繰り返します。

  6. 開店時間と閉店時間を今と比べてみてください。

日付を変更する必要がある場合は、常にNSCalendarandを使用する必要がありNSDateComponentsます。なぜそれほど重要なのかについては、この回答をご覧ください。

于 2011-08-27T14:02:29.473 に答える
1

より明確な解決策は、時間/分のコンポーネントのみが存在する NSDate オブジェクトを使用することだと思います。

基本的に、アプリのどこかに、ショップの開店時間と閉店時間を次のように保存する必要があります。

NSCalendar *calendar = [[NSCalendar alloc] 
                         initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *openTime = [[NSDateComponents alloc] init];
[openTime setHour: 12];
[openTime setMinute: 30];
NSDate *openDate = [calendar dateFromComponents: openTime];
[calendar release];

また、現在の時刻がそのような 2 つの NSDate オブジェクトの間にあるかどうかを確認する必要がある場合は、次のようなメソッドを使用できます。

- (BOOL)currentTimeIsInBetween: (NSDate *)date1 andDate: (NSDate *)date2 {
    NSCalendar *calendar = [[NSCalendar alloc] 
                             initWithCalendarIdentifier: NSGregorianCalendar];
    NSDateComponents *currentComponents = [calendar components: 
                                   (NSMinuteCalendarUnit | NSHourCalendarUnit)
                                          fromDate: [NSDate date]];
    NSDate *currentAdjusted = [calendar dateFromComponents: currentComponents];
    [calendar release];

    if ([currentAdjusted compare: date1] == NSOrderedAscending)
        return NO;

    if ([currentAdjusted compare: date2] == NSOrderedDescending)
        return NO;

    return YES;
}

編集: ユーザー rbrown は私よりも少し速かったようです。同じアプローチを提案しています。

于 2011-08-27T14:12:53.067 に答える
0

あなたはこのようなことをすることができます。

NSDate *today = // code for getting today date at 0 oclock
NSDate *now = [NSDate date];
double second = [now timeIntervalSinceDate:today];

これで、1日の始まりから秒単位で比較することができます。

于 2011-08-27T13:06:46.850 に答える