如何始终获取日期的秒值“ 00
” UIDatePicker
?
现在我得到了这种格式的价值5:30:45
,我需要得到这种格式的时间5:30:00
。
如何做到这一点?
如何始终获取日期的秒值“ 00
” UIDatePicker
?
现在我得到了这种格式的价值5:30:45
,我需要得到这种格式的时间5:30:00
。
如何做到这一点?
我使用了这段代码,它工作正常。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:datePicker.date];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:datePicker.date];
[dateComponents setHour:[timeComponents hour]];
[dateComponents setMinute:[timeComponents minute]];
[dateComponents setSecond:0.0];
NSDate *newDate = [calendar dateFromComponents:dateComponents];
您不必处理 NSDateComponents 或将日期转换为字符串并返回。您只需告诉日历将日期设置为分钟的开头(小时/日期/周/...)
NSDate *date = self.datePicker.date;
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMinute
startDate:&date
interval:NULL
forDate:date];
//date now is set to the beginning of the minute -> seconds == 00
NSDate *currentDate = [datePicker date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *Str_Seccond=[dateFormatter stringFromDate:currentDate];
在 Str_Seccond 字符串中,您可以获得字符串格式的秒数。
斯威夫特 4 版本:
let calendar = NSCalendar.current
let components = calendar.dateComponents([.year, .month, .day,
.hour, .minute],
from: yourDate)
let date = calendar.date(from: components)
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"ss"];
NSLog(@"%@",[dateformatter stringFromDate:[datePicker date]]);
在斯威夫特:
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute], fromDate: datePicker.date)
let date = calendar.dateFromComponents(components)