2011-05-05 102 views
4

我必須從日期發送DDMMYYY日期才能與API通信。將NSDate格式化爲DDMMYYYY?

NSDateComponents * dateComponents; NSCalendar * gregorian; NSDate * date;

gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

dateComponents = [[NSDateComponents alloc] init]; 
self.date = [gregorian dateByAddingComponents:dateComponents toDate:[NSDate date] options:0]; 

我是否必須使用[dateComponents day]等等?有沒有什麼方法可以幫助我像在PHP中一樣執行該任務?

回答

14

試試這個

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"ddMMyyyy"]; 
NSString *textDate = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:[NSDate date]]]; 
NSLog(@"Date %@",textDate); 
[dateFormatter release]; 
+0

該代碼運行得非常好:-)再次感謝您7KV7 – clement 2011-05-05 07:47:54

+0

缺少分號;在NSLog聲明的末尾,但其他方面完美無缺! – jsherk 2012-12-12 00:00:40

1

剛:

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; 
    [outputFormatter setDateFormat:@"ddMMyyyy"]; 
    NSString *textDate = [NSString stringWithFormat:@"%@",[outputFormatter stringFromDate:[NSDate date]]]; 
    [outputFormatter release]; 
1

試試這個代碼:

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]]; 
[dateFormatter setDateFormat:@"ddMMyyyy"]; 
NSDate *current = [NSDate date]; 
NSString *currentstring = [dateFormatter stringFromDate:current] 
0

試試這個:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 

[dateFormatter setDateFormat:@"ddMMyyyy"]; 

NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]); 
1
NSDate *date=[NSDate date]; 
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init]; 
    [formatter setDateFormat:@"ddMMyyyy"]; 
    NSString *dateOfGame =[formatter stringFromDate:date]; 
    [formatter release]; 
+0

終於聽起來不難,但我不得不知道語言的所有可能性......哼:-) – clement 2011-05-05 07:48:46

+0

語言的所有可能性?我不明白我的 – Gypsa 2011-05-05 08:00:29

+0

xcode可以做什麼;) – clement 2011-05-05 08:25:40

0

同意隨着魯本·埃斯波西託

只要改變你這樣的代碼。

NSDateFormatter *dtFormatter = [[NSDateFormatter alloc]init]; 
[dtFormatter setDateFormat:@"ddMMyyyy"];  
NSString *strDate = [NSString stringWithFormat:@"%@",[dtFormatter stringFromDate:[NSDate date]]]; 
[dtFormatter release]; 
NSLog(@"%@",strDate);