将字符串转换为日期时间 [星期三 Mar 01, 2017 6:00 AM] 这种格式在 c# 中



我有带有日期和时间列的 excel 工作表,日期格式是这个Wed Mar 01, 2017,而时间格式是这个6:00 AM我从 excel 工作表中获取 vales 并将这两列与之间的空格组合在一起,使其Wed Mar 01, 2017 6:00 AM看起来像这样。现在我想将此字符串转换为日期时间。我已经尝试了很多事情,但我收到字符串不是有效日期时间格式的错误。

string startDate = row.Cells[0].Value.ToString();
 string startTime = row.Cells[1].Value.ToString();
 var mydate = startDate+ " " + startTime; // it creates Wed Mar 01, 2017 6:00 AM, this is shown in debugger
 DateTime finaldate = DateTime.ParseExact(mydate, "r", null);

我希望它以相同的格式转换为日期时间,因为我有另一列告诉我这个时间也增加了小时数,我正在使用addHours()来做到这一点。 所以我希望在添加小时后以相同的格式输出。我无法使这种格式的日期格式字符串提供给ParseExact。任何帮助,不胜感激。谢谢

您可以指定自定义格式:

DateTime finaldate = DateTime.ParseExact(mydate, "ddd MMM dd, yyyy h:mm tt", CultureInfo.InvariantCulture);

最新更新