我知道这里有很多与此主题有关的问题。但是,我似乎无法解决我的问题。
我有这个字符串,例如“2013-08-26 12:11:51 10:17:25”,我只想抓取“2013-08-26”,然后将其转换回字符串。我尝试了很多方法都没有成功:
NSMutableString *visitDate = [[NSMutableString alloc] initWithString:@"2013-08-26 10:17:25"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:visitDate];
NSLog(@"date: %@", date);
NSMutableString *returnConvertedDateString = [[NSMutableString alloc]initWithString:(NSMutableString *)date];
NSLog(@"converted string: %@", returnConvertedDateString);
上面 NSLog 语句的结果是:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSPlaceholderMutableString initWithString:]: nil argument'
我也试过:
- (NSMutableString *) convertDateToString : (NSMutableString *)visitDate{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:(NSDate *)visitDate];
NSMutableString *returnConvertedDateString = [[NSMutableString alloc]initWithFormat:@"%ld-%ld-%ld", (long)[components year], (long)[components month],(long)[components day]];
return returnConvertedDateString;
}