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

纵饮孤独 提交于 2019-12-03 02:52:27
Rob

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]];
Adarsh G J
  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);

You can get like this

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!