Search code examples
iosdatensdate

iOS 8 - get current date as DD/MM/YYYY


Can anybody give me some code how I get the date?

NSDateComponents *components = [[NSCalendarcurrentCalendar] component:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYearfromDate:[NSDatedate]]; 

NSString *day = [components day]; 
NSString *week = [components month]; 
NSString *year = [components year]; 

NSString *date = [NSString stringWithFormat:@"%@.%@.%@",day,week,year];

^^ my code is not working :S

And is there a way that I can get the date of tomorrow, in 1 week and so on...

Thanks :)


Solution

  • You can either use a variation of your code that retrieves the numeric components using NSCalendar with the components method:

    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    
    NSInteger day = [components day];
    NSInteger month = [components month];
    NSInteger year = [components year];
    
    NSString *string = [NSString stringWithFormat:@"%ld.%ld.%ld", (long)day, (long)month, (long)year];
    

    Note, that's components, not component.

    Or, better, you can use NSDateFormatter:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"d.M.yyyy";
    NSString *string = [formatter stringFromDate:[NSDate date]];