将NSDate格式化为DDMMYYYY?

时间:2011-05-05 07:27:57

标签: ios nsdate nscalendar nsdatecomponents

我必须从日期发送DDMMYYY日期以与API通信。

NSDateComponents * dateComponents; NSCalendar *格里高利; NSDate * date;

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

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

我必须使用[dateComponents day]等吗?是否有一些方法可以帮助我像PHP一样执行该任务?

7 个答案:

答案 0 :(得分:14)

试试这个

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

答案 1 :(得分:1)

只需:

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

答案 2 :(得分: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]

答案 3 :(得分:1)

答案 4 :(得分:1)

    NSDate *date=[NSDate date];
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"ddMMyyyy"];
    NSString *dateOfGame =[formatter stringFromDate:date];
    [formatter release];

答案 5 :(得分:0)

试试这个:

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

[dateFormatter setDateFormat:@"ddMMyyyy"];

NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);

答案 6 :(得分:0)

同意 Ruben Esposito

只需更改您的代码即可。

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