Convert an hour-and-minute NSDate to a full NSDate
suggest changeSometimes an NSDate is built from only an hour and minute, for example 08:12.
That value has no meaningful day, month, year, or time zone, so it does not compare or combine cleanly with other NSDate values. Fill in those fields from “now” (or another known date).
In this example, hourAndMinute is an NSDate that carries only the hour and minute:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *hourAndMinuteComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute
fromDate:hourAndMinute];
NSDateComponents *componentsOfDate = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
fromDate:[NSDate date]];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay: componentsOfDate.day];
[components setMonth: componentsOfDate.month];
[components setYear: componentsOfDate.year];
[components setHour: [hourAndMinuteComponents hour]];
[components setMinute: [hourAndMinuteComponents minute]];
[components setSecond: 0];
[calendar setTimeZone: [NSTimeZone defaultTimeZone]];
NSDate *yourFullNSDateObject = [calendar dateFromComponents:components];
yourFullNSDateObject now has a calendar day as well as the original hour and minute.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents