是否可以从此列表中检查并解析仅日期:
List<string> everything = new List<string>
{"1", "A", "11/05/2013 22:43", "2.3", "21/11","null", "2012"};
这应该只返回11/05/2013 22:43
的解析值
不应返回值2.3
和21/11
。
答案 0 :(得分:2)
使用DateTimke.TryParse
。您可以使用以下LINQ查询:
IEnumerable<DateTime> dates = everything
.Select(str => str.TryGetDate(CultureInfo.InvariantCulture))
.Where(d => d.HasValue)
.Select(d => d.Value);
TryGetDate
遵循扩展,这对LINQ查询很方便:
public static DateTime? TryGetDate(this string item, params IFormatProvider[] formatProvider)
{
if (formatProvider.Length == 0)
formatProvider = new[]{ CultureInfo.CurrentCulture };
bool success = false;
DateTime d = DateTime.MinValue;
foreach (var provider in formatProvider)
{
success = DateTime.TryParse(item, provider, DateTimeStyles.None, out d);
if (success) break;
}
return success ? (DateTime?)d : (DateTime?)null;
}
结果:
Console.WriteLine(string.Join(", ", dates)); // 11/05/2013, 02/03/2013
修改:因为您要解析完全使用DateTime.TryParseExact
。这是另一种返回所需结果的方法:
public static DateTime? TryGetDateExact(this string item, String[] allowedFormats = null, params IFormatProvider[] formatProvider)
{
if (formatProvider.Length == 0)
formatProvider = new[] { CultureInfo.CurrentCulture };
if (allowedFormats == null || allowedFormats.Length == 0)
{
allowedFormats = formatProvider
.Select(fp => {
DateTimeFormatInfo dti = DateTimeFormatInfo.GetInstance(fp);
return String.Format("{0} {1}", dti.ShortDatePattern, dti.ShortTimePattern);
})
.ToArray();
}
bool success = false;
DateTime d = DateTime.MinValue;
foreach (var provider in formatProvider)
{
success = DateTime.TryParseExact(item, allowedFormats, provider, DateTimeStyles.None, out d);
if (success) break;
}
return success ? (DateTime?)d : (DateTime?)null;
}
您可以这样使用它:
IEnumerable<DateTime> dates = everything
.Select(str => str.TryGetDateExact(null, CultureInfo.InvariantCulture))
.Where(d => d.HasValue)
.Select(d => d.Value);
请注意,我已使用CultureInfo.InvariantCulture
强制/
作为分隔符。如果只想将CultureInfo.CurrentCulture
与格式字符串一起使用,则可以省略所有参数。
答案 1 :(得分:1)
您可以使用DateTime.TryParse
:只需尝试解析列表中的每个字符串,如果解析成功,则为DateTime
http://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx
List<DateTime> datas = new List<DateTime>();
foreach (String st in everything) {
DateTime dateTime;
if (DateTime.TryParse(st, out dateTime)) // <- Probably you'll want to specify datetime formats here
datas.Add(dateTime);
}
答案 2 :(得分:0)
这会忽略“2.3”作为有效日期值
List<string> everything = new List<string> { "20131105", "1", "A", "11/05/2013 22:43", "2.3", "21/11", "null", "2012" };
List<string> allDates = new List<string>();
DateTime d;
foreach (string s in everything)
{
if (s.Length < 8) continue;
if (DateTime.TryParse(s, out d))
{
allDates.Add(s);
}
}