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

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

任何人都可以给我一些代码来获取日期吗?

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];

^^ 我的代码不工作 :S

有什么方法可以让我在 1 周内等得到明天的日期...

谢谢:)

试试这个,设置不同的组件单位:

    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];

如果你想得到其他日子,使用这个link calendar get other day

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

您可以使用代码的变体,使用 NSCalendarcomponents 方法检索数字组件:

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];

请注意,这是 components,而不是 component

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

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

你可以这样

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:Date())
print(dateString)