简体   繁体   中英

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.

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.

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?

You probably should store a single datetime (or datetime2 ) in the database, rather than separate date and time fields. But to address the casting issue - consider that time in SQL Server is mapped to TimeSpan in .NET.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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