how to check datetime has unassigned or default value?

beginer
beginer
Member
1328 Points
43 Posts

Is there any way apart from following?

//Checks if createdDate has no value
if (createdDate == "1/1/0001 12:00:00 AM")
// do something
Views: 10328
Total Answered: 2
Total Marked As Answer: 2
Posted On: 05-Jul-2021 21:55

Share:   fb twitter linkedin
Answers
Priya
Priya
Participant
936 Points
28 Posts
         

If you have a DateTime object, then the default value is DateTime.MinValue, and hence you have to check it like this:

DateTime createdDate= new DateTime();

if (createdDate==DateTime.MinValue)
{
     //unassigned
}

If the DateTime object is nullable, then here is a different story:

 DateTime? createdDate = null;

if (!createdDate.HasValue)
{
     //unassigned
}
Posted On: 06-Jul-2021 05:33
Thanks.
 - beginer  19-Jul-2021 21:21
Smith
Smith
None
2568 Points
74 Posts
         

We can create extension method to check empty or unassigned datetime object as

public static class DateTimeUtililty
{
    public static bool IsEmpty(this DateTime dateTime)
    {
        return dateTime == DateTime.MinValue;
    }
}

And can be used as:

if (createdDate.IsEmpty())
{
       //unassigned
}
Posted On: 07-Jul-2021 00:18
Thanks.
 - beginer  19-Jul-2021 21:21
 Log In to Chat