首页 > 解决方案 > 将excel中的日期和时间合并到数据库中

问题描述

我正在尝试从 excel 中的不同列获取日期和时间并写入数据库。例如在 excel 中

日期:23/01/2019

时间:18:30:00

需要读写的结果将是“2019-01-23 18:30:00”我做了谷歌一些解决方案并尝试了但仍然没有运气。

代码示例:

start.DateTime = DateTime.ParseExact(excelReader.GetDateTime(DatePOS) + " " + excelReader.GetDateTime(TimePOS),"yyyy-mm-dd hh:mm:ss",CultureInfo.InvariantCulture);

DatePOS/TimePOS 代表日期列和时间列的列位置,结果出现无效格式错误。当我检查声明并得到

GetDateTime(DatePOS) "23/01/2019 00:00:00"

GetDateTime(TimePOS) "30/12/1899 18:30:00"

start.DateTime "1/01/0001 00:00:00"

请帮忙,谢谢

标签: c#exceldatetime

解决方案


您应该使用GetString而不是GetDateTime。后者从 excel 列返回解析的日期。尝试这个

start.DateTime = DateTime.ParseExact(excelReader.GetString(DatePOS).Split(' ')[0] + " " + excelReader.GetString(TimePOS).Split (' ')[1],
                                     "yyyy-mm-dd hh:mm:ss",
                                     CultureInfo.InvariantCulture);

推荐阅读