10

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 :)

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Tim
  • 175
  • 1
  • 1
  • 12

4 Answers4

22

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]];
felixwcf
  • 2,078
  • 1
  • 28
  • 45
Rob
  • 415,655
  • 72
  • 787
  • 1,044
11
  NSDate *todayDate = [NSDate date]; //Get todays date 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // here we create NSDateFormatter object for change the Format of date. 
    [dateFormatter setDateFormat:@"dd-MM-yyyy"]; //Here we can set the format which we need 
    NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// Here convert date in NSString
NSLog("Today formatted date is %@",convertedDateString);

WG1
  • 84
  • 6
Adarsh G J
  • 2,684
  • 1
  • 24
  • 25
2

You can get like this

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:Date())
print(dateString)
Ucdemir
  • 2,852
  • 2
  • 26
  • 44
0

try this ,set the different components unit:

    NSDate *today = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents * components =
                        [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:today];
    NSInteger day = [components day];
    NSInteger month = [components month];
    NSInteger year = [components year];

if your want to get other days ,use this link calendar get other day

Community
  • 1
  • 1
Feng Lin
  • 670
  • 4
  • 8