Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using "Ticks" for being able to calculate with DateTime, what's wrong with that?

One of my tables has a FinishDate column, defined as DatTime? (mind the question mark), so I decided to work as follows in order to check if that field is filled in and if the date is longer than a year ago:

DateTime finish = to.FinishDate == null? DateTime.Now : (DateTime) (to.FinishDate);
if (DateTime.Now.Ticks - finish.Ticks > new DateTime(1,0,0).Ticks)

As an error message, I get that "Year, Month and Day parameters describe an un-representable DateTime".

I just want to check if the amount of ticks of the subtraction of the FinishDate and now is larger than the amount of ticks in a year.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I do that?

>Solution :

There is no 0 month and day in .NET’s DateTime, minimum DateTime is new DateTime(1,1,1), but just use default or DateTime.MinValue. For example:

var minTicks = new DateTime.MinValue.Ticks;

But you can just compare DateTimes between them, so to handle "FinishDate – Now > 1 year" case you can use (consider using UTC times on both sides, i.e. DateTime.UtcNow):

if (finish > DateTime.Now.AddYears(-1)) // updated from the comment by vc74
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading