-1

我知道这里有很多与此主题有关的问题。但是,我似乎无法解决我的问题。

我有这个字符串,例如“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;
}
4

4 回答 4

1

您的字符串中有重复的时间。假设这是一个错字,你可以像这样得到你想要的。

NSDateFormatter * dateFormatter = [NSDateFormatter new];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate * date = [dateFormatter dateFromString:@"2013-08-26 12:11:51"];

[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSString * dateString = [dateFormatter stringFromDate:date];

NSLog(@"%@", dateString);
于 2013-08-26T07:32:21.873 回答
0

假设日期时间字符串的格式是NSString *visitDate = @"2013-08-26 12:11:51 10:17:25";

试试这个方法:

-  (NSString *) convertDateToString:(NSString *)visitDate{
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\d{4}-\d{2}-\d{2})" options:NSRegularExpressionCaseInsensitive error:NULL];
  NSTextCheckingResult *firstMatch = [regex firstMatchInString:opening_time options:0 range:NSMakeRange(0, [visitDate length])];
  if (firstMatch) {
      NSRange range = [firstMatch rangeAtIndex:0];
      NSString *dateString = [urlString substringWithRange:range];
      return dateString;
  }
  return nil;
}

此方法应仅提取字符串的yyyy-MM-dd一部分并以字符串表示形式返回。如果需要,请记住将其修改为可变版本。

于 2013-08-26T07:27:08.797 回答
0

最简单的方法是

NSMutableString *visitDate = [[NSMutableString alloc] initWithString:@"2013-08-26 12:11:51"];

    NSArray *items = [visitDate componentsSeparatedByString:@" "];
    NSLog(@"%@",[items objectAtIndex:0]);
于 2013-08-26T07:31:19.203 回答
0

如果你想要一个字符串,为什么不只返回前 10 个字符呢?

[dateString substringToIndex:10];
于 2013-08-26T07:43:43.180 回答