Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your approach should work fine. I needed a solution for this type problem (setting the individual date components) and the following code works as expected for me. My situation: I wanted to create a date object that used the current date but had the time set to a value that was passed in as a string.</p> <pre><code>NSString *string = @"7:00"; NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; NSDateFormatter *timeOnlyFormatter = [[NSDateFormatter alloc] init]; [timeOnlyFormatter setLocale:locale]; [timeOnlyFormatter setDateFormat:@"h:mm"]; NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *today = [NSDate date]; NSDateComponents *todayComps = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:today]; NSDateComponents *comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[timeOnlyFormatter dateFromString:string]]; comps.day = todayComps.day; comps.month = todayComps.month; comps.year = todayComps.year; NSDate *date = [calendar dateFromComponents:comps]; [calendar release]; [timeOnlyFormatter release]; [locale release]; </code></pre> <p>One thing to note is that you really have to pay attention to time zones when you are judging whether a time appears to be accurate. For example, in my app, when you stop at a breakpoint, you will see the time in GMT (so it looks different than the input time, which is in my local time), but when the time is actually displayed on screen in the app, it is being formatted to display in the local timezone. You may need to take this into consideration to determine whether the result is <em>actually</em> different from what you would expect.</p> <p>If this does not help, can you elaborate on "not giving the desired result"? What result is it giving and how does that compare to what you expected?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload