Ios 如何将用户输入的字符串转换为NSDate对象
我将用户输入作为字符串,并希望以日期格式存储,但在打印回控制台后,它会给我Ios 如何将用户输入的字符串转换为NSDate对象,ios,objective-c,Ios,Objective C,我将用户输入作为字符串,并希望以日期格式存储,但在打印回控制台后,它会给我NULL 以下是我所做的: MyLog(@"\nPlease Enter Date"); scanf("%s",cDate); stringDate= [NSString stringWithCString:cDate encoding:1]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat
NULL
以下是我所做的:
MyLog(@"\nPlease Enter Date");
scanf("%s",cDate);
stringDate= [NSString stringWithCString:cDate encoding:1];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd-MM-yyyy"];
NSDate * incomeDate = [dateFormat dateFromString:sDate];
MyLog(@"Date Entered is %@",[dateFormat stringFromDate:incomeDate]);
您可以使用以下代码将字符串转换为日期,但请确保使用的日期格式与从用户处获取输入的日期格式相同
NSString *stringtoconvert = @"13-09-2014";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd-MM-yyyy"];
NSDate *date = [dateFormat dateFromString:stringtoconvert];
MyLog(@"Date Entered is %@",date);
确保您在dd-MM-yyyy中输入日期字符串,因为我可以看到您正在使用
[dateFormat setDateFormat:@“dd-MM-yyyy”]代码>我认为应该是NSDate*incomeDate=[dateFormat dateFromString:stringDate];sDate不应该是stringDate吗?反之亦然?