iOS 8 - 获取当前日期为DD/MM/YYYY

Tim*_*Tim 10 date nsdate ios

任何人都可以给我一些代码我如何得到约会?

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];
Run Code Online (Sandbox Code Playgroud)

^^我的代码无效:S

有没有办法让我可以在明天,1周内等到...

谢谢 :)

Rob*_*Rob 22

您可以使用代码的变体来NSCalendar使用以下components方法检索数字组件:

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];
Run Code Online (Sandbox Code Playgroud)

请注意,那components不是component.

或者,更好的是,您可以使用NSDateFormatter:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"d.M.yyyy";
NSString *string = [formatter stringFromDate:[NSDate date]];
Run Code Online (Sandbox Code Playgroud)


Ada*_*G J 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);
Run Code Online (Sandbox Code Playgroud)