Working with a DateTime instance without the time information

3

My tests had been running successfully, when "by magic" one of them began 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 the two dates being "equal" the test began to mysteriously fail. After debugar , I noticed that there was a difference of milliseconds which made the test fail (only then I noticed that the behavior was not strange).

That's all to ask:

  • What is the best practice for working with "pure" date with no time information?

  • DateTime (with date / time) useful in some case of date comparison?

  • asked by anonymous 21.11.2015 / 02:24

    2 answers

    4
      

    What is the best practice for working with a "pure" date with no time information?

    You can use the property DateTime.Date if you already have an instance of class 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 the times always equal to 00:00:00. Note that the DateTime.Now property also exists. which functions as the DateTime.Today, but returns the current time normally.

      

    DateTime (with date / time) useful in some case of date comparison?

    This will greatly depend on how the dates will be used in your application. If you are setting up a CMS application, such as a blog for example, you will want to know when a post was published with accurate information that contains the time as well.

        
    21.11.2015 / 02:30
    4

    It's even possible to have one type with only the date, but it's not necessary, just resetting the time. This can be built manually or if it is taken from somewhere outside, you have to ensure that it is zeroed. When you get the system date, then just get the date and not the time. DateTime.Now takes the time now. The DateTime.Today takes today's date .

    See working on dotNetFiddle .

        
    21.11.2015 / 02:31