Differentiate Datetime.Now and Datetime.Now.Date

Asked

Viewed 242 times

3

I have a test and would like to know when an attribute received DateTime.Now or DateTime.Now.Date, has how to differentiate when an attribute has received these values?

Note: Can be varied values, the intention is to know when a date is a simple date (no time) and a full date (with time).

2 answers

5


Only by language and . NET, no, because both return DateTime. What you can do is intuit this by checking in your variable if the number of seconds is equal to zero (which is what DateTime.Now.Date seek to make):

if (meuDateTime.TimeOfDay.TotalSeconds == 0) 
{
    Console.WriteLine("Aparentemente atribuição veio de DateTime.Now.Date.");
} else {
    Console.WriteLine("Atribuição veio de DateTime.Now.");
}

It is worth noting that this test does not have 100% accuracy, because nothing prevents DateTime.Now to be shot at the exact second zero of a given day, but that’s a bit remote from happening.

  • 1

    I thought about that second zero possibility too.

  • or meuDateTime == meuDateTime.Date, What seems a little strange Maybe :p

  • @Brunocosta The thing that must be heartbreaking to work with time must be the premise of having to ensure almost 0% failure.

  • @But with my solution I compare the day, month and year too. in his only compare the seconds.

1

Yes. First I would suggest using DateTime.Today today which is equivalent to DateTime.Now.Date.

For this very reason it is sufficient to make the following comparison:

if(data == data.Date)

EDIT: This comparison also checks the year, month and day

Browser other questions tagged

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