How to work with a Datetime instance without the time information

Asked

Viewed 253 times

3

My tests had been passing successfully, when "by magic" one of them started to fail:

var data1 = DateTime.Now.AddDays(1);
...processos
...processos
var data1 = DateTime.Now.AddDays(1);
Assert.Throws<DataException>(() =>
                p.ChecarDatas(data1, data1));

public static void EnsureDateIsGreaterOrEqualThan(DateTime startDate, DateTime endDate, string errorMessage)
{
    if (startDate <= endDate)
        throw new Exception(errorMessage);
}

Even though the two dates were "equal" the test began to mysteriously fail. After debugar, I noticed that there was a difference of thousandths of a second in what caused the test to fail (only then I noticed that the behavior was not strange).

All this to ask:

  1. What best practice to work with "pure" date without time information?

  2. DateTime (with date/time) is useful in some case of comparison of dates?

2 answers

4


What best practice to work with "pure" date without time information?

You can use the property DateTime.Date if you already have a class instance DateTime. It returns an instance of DateTime with time always equal to 00:00:00.

You can also use the static property DateTime.Today to get the current date with hours always equal to 00:00:00. Note that there is also property DateTime.Now which works like Datetime.Today, but returns the current time usually.

Datetime (with date/time) is useful in some case of comparison of dates?

This will depend a lot on how the dates will be used in your application. If you’re building a CMS application, like a blog for example, you’ll want to know when a post was posted with accurate information that contains the time as well.

4

It’s even possible to have a guy with just the date, but it’s not necessary, just have the time reset. This can be built manually or if you’re going to pick it up from somewhere outside, you have to make sure it’s zeroed. When you will get the system date, then just take the date and not the time. The DateTime.Now takes the time from now. The DateTime.Today takes today’s date.

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.