0

カウントダウン タイマーを作成していて、特定の日付までの残り時間 (時:分:秒) を出力する必要があります。Now とターゲット日付の間の時間間隔を取得する方法を見つけましたが、時間間隔を文字列としてフォーマットする方法がわかりません。NSDateFormater は NSTimeInterval で動作しますか?

4

3 に答える 3

5

NSTimeInterval秒単位です。除算と剰余を使用して分割し、フォーマットします (コードはテストされていません)。

NSString *timeIntervalToString(NSTimeInterval interval)
{
   long work = (long)interval; // convert to long, NSTimeInterval is *some* numeric type

   long seconds = work % 60;   // remainder is seconds
   work /= 60;                 // total number of mins
   long minutes = work % 60;   // remainder is minutes
   long hours = work / 60      // number of hours

   // now format and return - %ld is long decimal, %02ld is zero-padded two digit long decimal 
   return [NSString stringWithFormat:@"%ld:%02ld:%02ld", hours, minutes, seconds];
}
于 2011-08-14T21:01:29.040 に答える
3

最初に 2 つの NSDate オブジェクトを比較して、2 つの秒数の差を取得します。使用する必要がある NSDate メソッドは次のとおりです。

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

次に、秒を時間/分/秒に解析する関数を単純に記述できます。たとえば、これを使用できます (テストされていません):

-(NSDictionary*)createTimemapForSeconds:(int)seconds{
   int hours = floor(seconds /  (60 * 60) );

   float minute_divisor = seconds % (60 * 60);
   int minutes = floor(minute_divisor / 60);

   float seconds_divisor = seconds % 60;
   seconds = ceil(seconds_divisor);

   NSDictionary * timeMap = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithInt:hours], [NSNumber numberWithInt:minutes], [NSNumber numberWithInt:seconds], nil] forKeys:[NSArray arrayWithObjects:@"h", @"m", @"s", nil]];

   return timeMap;
}
于 2011-08-14T19:49:02.110 に答える
2

これは私のプロジェクトのコードです:

-(NSString*)timeLeftString
{
    long seconds = [self msLeft]/1000;
    if( seconds == 0 )
        return @"";
    if( seconds < 60 )
        return [NSString stringWithFormat:
            pluralString(seconds,
            NSLocalizedString(@"en|%ld second left|%ld seconds left", @"")), seconds];
    long minutes = seconds / 60;
    seconds -= minutes*60;
    if( minutes < 60 ) 
        return [NSString stringWithFormat: 
            NSLocalizedString(@"%ld:%02ld left",@""),
            minutes, seconds];    
    long hours = minutes/60;
    minutes -= hours*60;
    return [NSString stringWithFormat:
        NSLocalizedString(@"%ld:%02ld:%02ld left",@""),
        hours, minutes, seconds];    
}

msLeft--- ミリ秒単位で時間を返す関数 pluralString--- 値に応じてフォーマット文字列のさまざまな部分を提供する関数 (http://translate.sourceforge.net/wiki/l10n/pluralforms)

関数は、異なるタイマー値に対して異なる形式を返します (残り 1 秒、残り 5 秒、残り 2:34、残り 1:15:14)。

いずれにせよ、長い操作中に進行不良が表示されるはずです

もう1つの考え: 残り時間が「短い」(1分未満?)場合、おそらく残り時間は表示されるべきではありません.

于 2013-01-02T10:06:57.390 に答える