-3

私は方法を持っています:

- (NSString *)intervalSinceNow: (NSString *) theDate 
{



NSDateFormatter *date=[[NSDateFormatter alloc] init];
[date setDateFormat:@"yyyy-MM-dd HH:mm "];
NSDate *d=[date dateFromString:theDate];

NSTimeInterval late=[d timeIntervalSince1970]*1;


NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval now=[dat timeIntervalSince1970]*1;
NSString *timeString=@"";

NSTimeInterval cha=now-late;

if (cha/3600<1) {
    timeString = [NSString stringWithFormat:@"%f", cha/60];
    timeString = [timeString substringToIndex:timeString.length-7];
    timeString=[NSString stringWithFormat:@"%@m before", timeString];

}
if (cha/3600>1&&cha/86400<1) {
    timeString = [NSString stringWithFormat:@"%f", cha/3600];
    timeString = [timeString substringToIndex:timeString.length-7];
    timeString=[NSString stringWithFormat:@"%@ hour before", timeString];
}
if (cha/86400>1)
{
    timeString = [NSString stringWithFormat:@"%f", cha/86400];
    timeString = [timeString substringToIndex:timeString.length-7];
    timeString=[NSString stringWithFormat:@"%@ day before", timeString];

}

return timeString;
}

intervalSinceNow(2012-07-04T00:16:12Z) を呼び出すと、15525 日前に表示されます。解決方法を教えてください。

4

2 に答える 2

1

これらの計算を自分でやろうとさえしないのが最善です。とりわけ、ローカル ユーザーが使用しているカレンダー システムがわかりません。

システムで必要なことを行う手順は次のとおりです。 - ISO8601 日時を NSDate のインスタンスに変換します - ユーザーのロケールとローカル タイム ゾーンで NSDate を表示します

NSDateFormatterこれらの手順は、2 つのオブジェクトを使用して実行できます。1 つは日時文字列を NSDate に変換し、Zulu 用に構成するように設定し、もう 1 つはユーザーの現在のロケールとタイム ゾーンの日付をフォーマットするように設定します。既定のNSDateFormatterオブジェクトは、ユーザーの現在の設定に対して既に構成されています。

コードで行う必要があるのは、次のようなことだけです。

- (NSString*)localDateStringForISODateTimeString:(NSString*)ISOString
{
  // Configure the ISO formatter
  NSDateFormatter* isoDateFormatter = [[NSDateFormatter alloc] init];
  [isoDateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
  [isoDateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

  // Configure user local formatter (configure this for how you want
  // your user to see the date string)
  NSDateFormatter* userFormatter = [[NSDateFormatter alloc] init];
  [userFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

  // Convert the string -- this date can now also just be used
  // as the correct date object for other calculations and/or
  // comparisons
  NSDate* date = [isoDateFormatter dateFromString:ISOString];

  // Return the string in the user's locale and time zone
  return [userFormatter stringFromDate:date];
}

ここから返された文字列を印刷または表示すると、「2012-07-04T00:16:12Z」を指定した例の文字列は、(ニューヨークでは)「2012-07-03 20:16」と表示されます。上記のコード。

編集:上記のコードはARC環境を想定していることに注意してください。ARC を使用していない場合autoreleaseは、2 つの日付フォーマッタの作成にメッセージを追加してください。そうしないと、漏洩します。

于 2012-07-04T07:19:59.323 に答える
0
NSDateFormatter *date=[[NSDateFormatter alloc] init];
[date setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z' "];
NSDate *d=[date dateFromString:theDate];
NSTimeInterval late=[d timeIntervalSinceNow];

これらの行を次のように変更して、もう一度やり直してください

于 2012-07-04T07:16:01.783 に答える