本文介绍了如何在NSDate变量中只设置时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有NSDate变量,只想更改时间(不应更改日期)。是否有可能?

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

例如:用户在DatePicker日期选择日期间隔(如果是开始日期我想将时间设置为00:00:00,如果它是结束日期,我将时间定为23:59:59)

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)

感谢大家的帮助。

此致,Alex 。

推荐答案

你会想要使用。

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];

这篇关于如何在NSDate变量中只设置时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 12:22