;

How to Check if a DateTime is Null or not Null or Empty in C#


Tutorialsrack 10/02/2021 C#

In this article, you will learn how to check if a DateTime is Null or Not Null or Empty in C#. In this article, we used the two ways to check if the Datetime is Null or Not Null or Empty. 

Here are the examples to check if a DateTime is null or not null or empty in C#.

Example 1: using DateTime==null Condition Check

Example 1: using DateTime==null Condition Check
using System;

namespace Tutorialsrack
{
    class Program
    {
        /* How to Check if a DateTime Field is Null or not Null or Empty in C# */
        static void Main(string[] args)
        {

            DateTime Date = new DateTime(2020, 02, 05);
            DateTime? NullDate =null;

            Console.WriteLine("Datetime is Null or Empty: {0}",IsDateTimeNullorEmpty(Date));
            Console.WriteLine("Datetime is Null or Empty: {0}", IsDateTimeNullorEmpty(NullDate));
            //Hit ENTER to exit the program
            Console.ReadKey();
        }

        public static bool IsDateTimeNullorEmpty(DateTime? date)
        {
            return date == null ? true : false;
        }
    }
}
Output

Datetime is Null or Empty: False

Datetime is Null or Empty: True

Example 2: Using !DateTime.HasValue Condition Check

Example 2: Using !DateTime.HasValue Condition Check
using System;

namespace Tutorialsrack
{
    class Program
    {
        /* How to Check if a DateTime Field is Null or not Null or Empty in C# */
        static void Main(string[] args)
        {

            DateTime Date = new DateTime(2020, 02, 05);
            DateTime? NullDate =null;

            Console.WriteLine("Datetime is Null or Empty: {0}", IsDateTimeNullorEmpty1(Date));
            Console.WriteLine("Datetime is Null or Empty: {0}", IsDateTimeNullorEmpty1(NullDate));

            
            //Hit ENTER to exit the program
            Console.ReadKey();
        }

        public static bool IsDateTimeNullorEmpty1(DateTime? date)
        {
            return !date.HasValue ? true : false;
        }
    }
}
Output

Datetime is Null or Empty: False

Datetime is Null or Empty: True

I hope this article will help you to understand how to check if a DateTime is Null or Not Null or Empty in C#.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags