0

Say I want to create a date at "3:00 pm Friday".

I know today is Monday (day = 1). Friday is day 6. I know the hour I want to create is 15.

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:6];
[comps setMonth:currentDate.month];
[comps setYear:currentDate.year];

NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];

This might work in some cases I guess. But not if Friday is in a different month or year than today. Is there a robust solution to this, or do I have to manually account for the edge cases I mentioned?

EDIT: I don't know the day of the month or the year of the proposed date. I know today's date. I only know the day of the proposed date, and that it's the next date with that day from now. So, the next upcoming Friday from now, at 3:00 pm.

soleil
  • 12,133
  • 33
  • 112
  • 183
  • 1
    FYI - Monday is day 2, not 1. And `setDay` is for the day of the month, not the weekday. So setting it to `6` is the 6th of the month, not Friday. – rmaddy Sep 22 '14 at 23:24

1 Answers1

1

I am not sure I fully understand what you need, but you could build a 'string date' and convert it to NSDate:

NSString *dateFormat  @"MM/dd/yyyy hh:mm a";
NSString *myDateString = @"09/22/2014 16:30 pm";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:dateFormat];
preselectedDate = [df dateFromString: myDateString];
Marcelo Ribeiro
  • 1,718
  • 1
  • 13
  • 27
  • See my EDIT. I don't know that it's Sept 22 2014. I only know that it's the next upcoming Friday at 3:00. Friday at 3:00 could be in the next month or year for all I know. – soleil Sep 22 '14 at 23:42
  • Got it. In this case maybe this is what you need? http://stackoverflow.com/questions/12829705/programmatically-getting-the-date-next-sunday-at-5pm – Marcelo Ribeiro Sep 22 '14 at 23:44