简体   繁体   English

无法分别解析日期和时间

[英]Unable to parse date and time separately

I have a following code that read data from a SQL Data reader and put it into a collection. 我有以下代码,这些代码从SQL数据读取器读取数据并将其放入集合中。

while (sdr.Read())
{
    itemFeed.Add(new Item
    {
        itemTypeId = (int)sdr.GetValue(0),
        itemDate = (DateTime)sdr.GetValue(5), //Incoming: 2014-09-07
        itemTime = (DateTime)sdr.GetValue(6), //Incoming: 21:29:18.1030000
    });
    i++;
}

Issue is when the incoming value of 2014-09-07 is converted into date time it automatically adds time to it and it becomes 2014-09-07T00:00:00 , and for casting the time it fails because of invalid format. 问题是,当2014-09-07的传入值转换为日期时间时,它会自动为其添加时间,并变为2014-09-07T00:00:00 ,并且由于无效格式,转换时间失败。

I understand that this is because its a date time object but again there are no separate objects for date and time in .net so how can i parse them separately as they are? 我知道这是因为它是一个日期时间对象,但是.net中又没有单独的日期和时间对象,所以我怎样才能分别解析它们呢?

You probably should store a single datetime (or datetime2 ) in the database, rather than separate date and time fields. 您可能应该在数据库中存储单个datetime (或datetime2 ),而不是单独的datetime字段。 But to address the casting issue - consider that time in SQL Server is mapped to TimeSpan in .NET. 但是要解决转换问题,请考虑将SQL Server中的time映射到.NET中的TimeSpan

var date = (DateTime)sdr.GetValue(5);
var time = (TimeSpan)sdr.GetValue(6);
var dateTime = date.Add(time);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM