how to check datetime has unassigned or default value?

beginer
beginer
240 Points
70 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: 91
Total Answered: 2
Total Marked As Answer: 2
Posted On: 05-Jul-2021 21:55

Share:   fb twitter linkedin
Answers
Priya
Priya
Member
150 Points
40 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
Participant
610 Points
140 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