How can I set only time in NSDate variable?

…衆ロ難τιáo~ 提交于 2020-01-01 04:33:05

问题


I have NSDate variable and would like to change only time (date shouldn't be changed). Is it possible ?

Eg: user pick date interval in DatePicker date (If it's start date I would like to set time as 00:00:00, if it's end date, I set time as 23:59:59)

Thanks all for your help.

Regards, Alex.


回答1:


You'll want to use NSDateComponents.

NSDate *oldDate = datePicker.date; // Or however you get it.
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:unitFlags fromDate:oldDate];
comps.hour   = 23;
comps.minute = 59;
comps.second = 59;
NSDate *newDate = [calendar dateFromComponents:comps];



回答2:


The NSDate object cannot be changed.

You can create a new NSDate object from it. Take a look at the - (id)dateByAddingTimeInterval:(NSTimeInterval)seconds method.

NSDate *newDate = [endDate dateByAddingTimeInterval:24.0f * 60.0f * 60.0f - 1.0f];



回答3:


When I only need to track the time, I don't use NSDate or NSTimeInterval. Instead I use an NSinteger and store the "military" time, ie 0830 = 8:30 AM, 14:15 = 2:15 PM.



来源:https://stackoverflow.com/questions/17659314/how-can-i-set-only-time-in-nsdate-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!