我想将字符串转换为 DateTime 对象。我的字符串将采用这种格式 - “2016 年 7 月 18 日”(日期可以更改)。显然,.Net 不将此作为有效的日期格式。有什么简单的方法可以在不使用任何第三方库的情况下进行转换吗?
最佳答案
我不会使用 String.Replace
,因为这可能是一个问题,因为当前区域性的月份名称包含您要替换的字符串。
相反,您可以从字符串中删除这部分:
string input = "18th Jul 2016";
string[] token = input.Split(); // split by space, result is a string[] with three tokens
token[0] = new string(token[0].TakeWhile(char.IsDigit).ToArray());
input = String.Join(" ", token);
DateTime dt;
if(DateTime.TryParseExact(input, "dd MMM yyyy", null, DateTimeStyles.None, out dt))
{
Console.WriteLine("Date is: " + dt.ToLongDateString());
}
如果将 null
作为 IFormatProvider
传递给 TryParseExact
使用当前区域性的日期时间格式。如果你想强制使用英文名称,你可以传递 CultureInfo.InvariantCulture
。
关于c# - 转换为日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38432184/