08Convert NSDate that is composed from hour and minute only to a full NSDate

suggest change

There are many cases when one has created an NSDate from only an hour and minute format, i.e: 08:12 that returns from a server as a String and you initiate an NSDate instance by these values only.

The downside for this situation is that your NSDate is almost completely “naked” and what you need to do is to create: day, month, year, second and time zone in order to this object to “play along” with other NSDate types.

For the sake of the example let’s say that hourAndMinute is the NSDate type that is composed from hour and minute format:

Objective-C

NSDateComponents *hourAndMinuteComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute
                                                         fromDate:hourAndMinute];
NSDateComponents *componentsOfDate = [[NSCalendar currentCalendar] 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];

Now your object is the total opposite of being “naked”.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents