9

如何始终获取日期的秒值“ 00UIDatePicker

现在我得到了这种格式的价值5:30:45,我需要得到这种格式的时间5:30:00

如何做到这一点?

4

6 回答 6

14

我使用了这段代码,它工作正常。

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];  
于 2012-08-18T13:50:11.253 回答
7

您不必处理 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
于 2013-05-15T16:28:50.607 回答
4
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 字符串中,您可以获得字符串格式的秒数。

于 2012-08-18T12:50:16.020 回答
2

斯威夫特 4 版本:

 let calendar = NSCalendar.current
 let components = calendar.dateComponents([.year, .month, .day,
                                           .hour, .minute], 
                                           from: yourDate)
 let date = calendar.date(from: components)
于 2018-10-09T10:00:15.133 回答
1
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"ss"];
NSLog(@"%@",[dateformatter stringFromDate:[datePicker date]]);
于 2012-08-18T12:50:37.203 回答
1

在斯威夫特:

let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute], fromDate: datePicker.date)
let date = calendar.dateFromComponents(components)
于 2016-08-17T08:33:53.857 回答