Home > OS >  Incomplete DateTime to a complete DateTime comparison
Incomplete DateTime to a complete DateTime comparison

Time:09-21

I have a data type column in my SQL Server database. And it's signature is following: date (yyyy-mm-dd) thus another column with tinyint representing the hour. While another table contains a full datetime column (yyyy-mm-dd hh:mm:ss.fff) There are no mm,ss,fff values. Everything is at 0. But hour is there..

I need to compare these two with Entity Framework.

I know how it would be easy with two datetimes, but it's just how it is

Now I have a Model in my C# code. And they are both DateTime type. And I don't know how to compare them correctly. It would be great, if I could make an anonymous type, where I could add this tinyint (or byte in C#) to this new (another DateTime) and add hour from the hour column. But..

The property 'System.DateTime.Hour' has no setter

I don't know how to do this. And there is not that much info on Internet regarding this.

Is it really incomparable? Or there is a way to do this?

CodePudding user response:

I'm not sure to understand exactly what you want to do but: If you want to add hours to an existing DateTime, you need to add a TimeSpan to this DateTime.

var date = DateTime.Now;

date = date   TimeSpan.FromHours(5); // adds 5 hours to the date

You can just replace the "5" by your tinyint value.

Edit As you seems to struggle a bit understanding my simple example, a code closer than the one you should have on your side:

DateTime alreadyCompleteDate = ... // get the value from your database complete datetime column

DateTime incompleteDate = ... // get the value from your database incomplete datetime column
int hours = ... // get the number of hours to add to incompleteDate from your database tinyint column

DateTime completeDateTime = incompleteDate   TimeSpan.FromHours(hours);

// or whatever comparison you willing to do
var comparisonResult = alreadyCompleteDate < completeDateTime; // this works
  • Related