私はUIDatePicker
30分間隔でしか時間がかからない. 現在の時刻を 30 分単位viewDidLoad
で取得したい。どうすればこれを行うことができますか?
質問する
1190 次
1 に答える
4
NSDateComponents
日付の時と分を取得して操作するために使用します。これが私がそれをした方法です:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) //Need to pass all this so we can get the day right later
fromDate:[NSDate date]];
[components setCalendar:calendar]; //even though you got the components from a calendar, you have to manually set the calendar anyways, I don't know why but it doesn't work otherwise
NSInteger hour = components.hour;
NSInteger minute = components.minute;
//my rounding logic is maybe off a minute or so
if (minute > 45)
{
minute = 0;
hour += 1;
}
else if (minute > 15)
{
minute = 30;
}
else
{
minute = 0;
}
//Now we set the componentns to our rounded values
components.hour = hour;
components.minute = minute;
// Now we get the date back from our modified date components.
NSDate *toNearestHalfHour = [components date];
self.datePicker.date = toNearestHalfHour;
お役に立てれば!
于 2012-10-05T07:32:32.267 に答える