2015-01-06 17 views
9

Qualcuno può darmi un codice come ottengo la data?iOS 8 - ottenere la data corrente come GG/MM/AAAA

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

^^ il mio codice non funziona: S

E c'è un modo che io possa avere la data di domani, in 1 settimana e così via ...

Thanks :)

+2

Google "NSDateFormatter". –

+2

Definire "non funzionante". – rmaddy

+0

Come è questa domanda fuori tema? Non sta chiedendo a nessuno di "raccomandare o trovare un libro, uno strumento, una libreria di software, un tutorial o altra risorsa fuori sito". – Suragch

risposta

22

è possibile utilizzare una variante del codice che recupera i componenti numerici utilizzando NSCalendar con il metodo 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]; 

Nota, che è components, non component.

O, meglio, è possibile utilizzare NSDateFormatter:

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

provare questo, impostare le diverse unità componenti:

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

se il tuo vuole ottenere altri giorni, utilizzare questo l inchiostro calendar get other day

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

0

È possibile ottenere in questo modo

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