Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set only time in NSDate variable?

Tags:

ios

nsdate

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.

like image 944
LIAL Avatar asked Jul 15 '13 16:07

LIAL


2 Answers

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];
like image 110
Kevin Avatar answered Nov 13 '22 06:11

Kevin


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];
like image 28
picciano Avatar answered Nov 13 '22 05:11

picciano