1

All,

I have a method that takes a date (YYYY-MM-DD H:M:S) from the database and creates a URL with the year, month and day components from the date string. My solution works but I was wondering if there is a better way to do this? How are the cool kids doing it? :-)

Thanks!

   -(NSString *) prettyURLFrom:(NSString *)dateString{



    NSString * URLString = @"";
    NSString *URL = @"http://www.theblues.com/featured/article/";

    NSArray *myWords = [dateString componentsSeparatedByCharactersInSet:
                        [NSCharacterSet characterSetWithCharactersInString:@"-\" \" :"]
                        ];


    URLString = [NSString stringWithFormat:@"%@%@/%@/%@", 
                    URL,
                    [myWords objectAtIndex:1],
                    [myWords objectAtIndex:2],
                    [myWords objectAtIndex:0]];



    return URLString;


   }
Slinky
  • 5,662
  • 14
  • 76
  • 130

2 Answers2

1

If you have NSDate object then you can use

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];

    NSInteger day = [components day];
    NSInteger month = [components month];
    NSInteger year = [components year];  

NSString to NSDate

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-DD HH:MM:SS"];

NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:@"1999-07-02 2:2:4"];
Parag Bafna
  • 22,812
  • 8
  • 71
  • 144
1

Like I said in the comments, I find it bizarre you're passing and returning values as strings when they probably should be NSDate and NSURL respectively.

I would probably do something like:

-(NSURL*)URLFromDate:(NSDate*)date
{
    // Assumes user uses a gregorian calendar
    NSDateComponents *dateComp = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:date];

    return [NSURL URLWithString:[NSString stringWithFormat:@"http://www.theblues.com/featured/article/%li/%li/%li"
                                    , [dateComp year]
                                    , [dateComp month]
                                    , [dateComp day]]];
}
  • Yes, you are right. Will do something like what you suggested. Thanks – Slinky Mar 30 '12 at 12:59
  • Just to clarify, for anyone working with the examples provided above - The solution that uses NSDateComponents above needs a format specifier %li, not %@ So: http://www.theblues.com/featured/article/%li/%li/%li Thanks to all for the help with this. – Slinky Mar 30 '12 at 13:07