2011-01-25 8 views
8

timestringの形式、たとえば2:00にあります。私はNSDateに現在dateと初期化したいと思います。 私は日付オブジェクトでこれを比較することはできませんよ特定時間でNSDateオブジェクトを初期化する

NSDateComponents *comps = [[NSDateComponents alloc] init]; 
    [comps setHour:2]; 

やってみました。

答えて

30

は、あなたがそれ以降の日付と比較することができるはず

NSDateComponents *comps = [[NSDateComponents alloc] init]; 
[comps setDay:6]; 
[comps setMonth:5]; 
[comps setYear:2004]; 

NSCalendar *gregorian = [[NSCalendar alloc] 
    initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDate *date = [gregorian dateFromComponents:comps]; 

を試してみてください助けてください。

多分あなたは何かのような意味です。私は今日の日付を使用して設定し、それからNSDateComponentsを作成して時間値を設定できると思います。

NSDate *today = [NSDate date]; 
NSCalendar *gregorian = [[NSCalendar alloc] 
         initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *weekdayComponents = 
        [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today]; 
[weekdayComponents setHour:12]; 
[weekdayComponents setMinute:10]; 
[weekdayComponents setSeconds:30]; 
+0

返事ありがとうございます。これは時刻コンポーネントでのみ設定する方法です。日付は現在の日付である必要があります。NSDate * mydate = [NSDate date]を使用して初期化されたDateオブジェクトの時間コンポーネントのみを変更することは可能です; – agupta

+0

あなたはこのようなことを意味すると思います。 – menapole

+0

はい迅速に返信いただきありがとうございます。 – agupta

2

あなたはNSDateNSDateComponentsを変換するNSCalendarオブジェクトを使用する必要があります。 Creating a Date from ComponentsのAppleのドキュメントを参照してください。

+0

replyに感謝します。NSDateの時間コンポーネントを設定することが可能です。現在の日付と時刻に初期化されたNSDateオブジェクトを取得できます。その後、時間コンポーネントを変更することは可能です。 – agupta

+0

同じカレンダーを使用してNSDateをNSDateComponentsに設定し、時刻を設定してから、カレンダーを使用してNSDateに戻します。 –

+0

返信いただきありがとうございます。 – agupta

3

NSDateを現在の日付で2に初期化するには、年、月、日のコンポーネントを含むNSDateを分割する必要があります。

NSDate *today = [NSDate date]; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *weekdayComponents = [gregorian 
             components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) 
             fromDate:today]; 
weekdayComponents.hour = 2; 

に時間を設定し、ちょうどのObjective Cの回答の一部を結集し、これらのコンポーネント

NSDate *todayAt2 = [gregorian dateFromComponents:weekdayComponents]; 
0

によって新しいNSDateを作成し、I(今)は、このヘルパー機能を持っています:

+ (NSDate*)dateForTodayAtHour:(NSUInteger)hour andMinutes:(NSUInteger)minutes { 
    NSDate* today = [NSDate date]; 
    NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 
    NSDateComponents* weekdayComponents = [gregorian components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:today]; 
    [weekdayComponents setHour:hour]; 
    [weekdayComponents setMinute:minutes]; 
    [weekdayComponents setSecond:0]; 
    NSDate* result = [gregorian dateFromComponents:weekdayComponents]; 
    return result; 
} 
関連する問題