2010-06-04 81 views
6

我在一個標籤中有2:01:20 PM格式;經過一些計算後,我需要更改該標籤的小時和/或分鐘。如何以編程方式在nsdate中設置小時分鐘?

也就是說,是否有可能通過將其轉換爲NSDate對象並修改像3:20:30 PM那樣的小時和分鐘來更改該標籤值?

這是否有任何setter方法?

+0

如果我使用 [字符串1 replaceCharactersInRange:NSMakeRange(0,5)withString: NSString stringWithFormat:@「%d:0%d」,小時,finalMinute] 我需要檢查大量的條件,如果分鐘小於10附加字符串作爲01,02,03 ....如果小時更大比9我需要更改範圍,因爲12:03:23 PM ..... – mac 2010-06-04 12:35:22

回答

1

如果您需要及時計算特定實例,例如3:20:30 PM 2010年10月23日,那麼你想使用NSCalendar,它可以讓你分解日期和做日期相關的計算。

警告字。日期和時間計算非常複雜和詳細。期望花費幾個小時來學習API。

+0

我的代碼是 NSDateFormatter * timeFormatter = [[[NSDateFormatter alloc] init] autorelease]; \t [timeFormatter setDateStyle:NSDateFormatterNoStyle]; \t [timeFormatter setTimeStyle:NSDateFormatterMediumStyle]; \t NSDate * stringTime = [NSDate date]; \t NSString * formattedDateStringTime = [timeFormatter stringFromDate:stringTime]; (@「時間字符串是%@」,formattedDateStringTime); \t \t time.text = formattedDateStringTime; 在這裏,我的問題是我需要改變時間小時,分鐘,所以,如果我遵循上面的評論其太難了,任何其他類,以使其輕鬆TechZen。 謝謝你快速回答。 – mac 2010-06-04 12:45:52

25

回答你的第一個問題 「?如何設置,小時,分鐘的NSDate的編程」 是以下幾點:

NSDate* result; 
    NSDateComponents *comps = [[NSDateComponents alloc] init]; 
    [comps setMinute:0]; 
    [comps setHour:0]; 
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    result = [gregorian dateFromComponents:comps]; 
    [comps release]; 
+0

它選擇日期爲「0001-01-01」。如何設置當前日期? – Satyam 2015-03-04 16:34:22

+1

這是你可以如何在組件中設置當前日期:'NSDateComponents * components = [日曆組件:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];' – iBug 2015-09-08 06:16:47

相關問題