-2

アプリケーションに次の形式の日付があります。

"MMM dd, yyyy hh:mm:ss a"

ユーザーがピッカーから日付を選択すると、日付は常にこの形式に変換されます。この形式から、正確に 24 時間後の日付を取得するにはどうすればよいですか?

たとえば、日付がMon 24 , 2012 17:44:33に変換するコードが必要な場合Tue 25 , 2012 17:44:33

4

3 に答える 3

2
  1. 日付と時刻のプログラミング ガイドをお読みください。

  2. 日付フォーマッタを使用して、文字列から日付を生成します。

  3. 日付に 1 日を追加します。

  4. 日付フォーマッタを使用して、新しい日付から文字列を生成します。

于 2012-07-18T14:04:09.677 に答える
1

次のコードを使用してNSDate、文字列から を作成します。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setCalendar:[NSCalendar currentCalendar]];
[dateFormatter setDateFormat:<FORMAT_OF_DATE_STRING>];
NSDate *date = [dateFormatter dateFromString:<DATE_STRING>];
[dateFormatter release];

に日数を追加するには、次のコードを使用しますNSDate

    NSDate *today =<YOUR_DATE>        
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    /*
     Create a date components to represent the number of days to add to the current date.         
     The weekday value for Sunday in the Gregorian calendar is 1, so add 1 from the number of days to subtract from the date in question.  (If today is Sunday, add 0 days.)    
     */
    NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];

    if(day<7)
    {
       [componentsToAdd setDay: day];
    }

    NSDate *calculateDay = [gregorian dateByAddingComponents:componentsToAdd
                                                      toDate:today options:0];

ハッピーコーディング!

于 2012-07-18T14:13:45.673 に答える
1

日付フォーマッタを設定するために必要なコードは次のとおりです。

NSString *dateString = @"Tue 24 , 2012 17:44:33";

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"EEE dd , yyyy HH:mm:ss"];

NSDate *theDate = [dateFormat dateFromString:dateString];

theDate = [NSDate dateWithTimeInterval:(60*60*24) sinceDate:theDate];

NSString *newDate = [dateFormat stringFromDate:theDate];

NSLog(@"%@",newDate);

コンソールは次を返します。

2012-07-18 09:26:28.395 TesterProject[71645:f803] Wed 25 , 2012 17:44:33

ただし、実際には月を含める必要があります。そうしないと、現在の月が必要になり、曜日がずれることがあるからです。

質問に入力した間違った形式ではなく、入力した日付の実際の形式を使用しました。日付のフォーマットについては、Unicode 標準を参照してください。

詳細についてNSDateFormatterは、Apple のドキュメント: NSDateFormatterを参照してください。

編集: これは別の実装です:

NSString *dateString = @"Tue 24 , 2012 17:44:33";

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"EEE dd , yyyy HH:mm:ss"];

NSDate *theDate = [dateFormat dateFromString:dateString];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

[offsetComponents setDay:1];

theDate = [gregorian dateByAddingComponents:offsetComponents toDate:theDate options:0];

NSString *newDate = [dateFormat stringFromDate:theDate];

NSLog(@"%@",newDate);

まったく同じものを返します。

于 2012-07-18T14:27:45.823 に答える