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

我的未来我决定 提交于 2019-12-20 14:12:08

问题


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


回答1:


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



回答2:


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




回答3:


You can get like this

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



回答4:


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



来源:https://stackoverflow.com/questions/27790657/ios-8-get-current-date-as-dd-mm-yyyy

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