Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime To Be NULL when the value is DateTime.MinValue or it is Null

Tags:

c#

datetime

In my console app I am attempting to format to HHmmss -> I am sure it is due to my data types but how can I have this be NULL when NULL and not display 1/1/0001 12:00:00 AM?

This is my syntax

public static DateTime fmtLST;
public static string LST = null;        
if (LST != null)
{
  IFormatProvider format = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
  fmtLST = DateTime.ParseExact(LST, "HHmmss", format);
}

Console.WriteLine(fmtLST.ToString("hh:mm:ss tt"));

If altered to public static DateTime? fmtLastScanTime; I get an error of

'No overload for method 'ToString' takes 1 arguments

How can I have this display NULL instead of 1/1/0001 12:00:00 AM? Trying to account for 1/1/0001 12:00:00 AM being displayed

like image 705
ToastedBread LeavesYouDead Avatar asked Jan 11 '17 04:01

ToastedBread LeavesYouDead


1 Answers

Nullable DateTime. A nullable DateTime can be null. The DateTime struct itself does not provide a null option. But the "DateTime?" nullable type allows you to assign the null literal to the DateTime type. It provides another level of indirection.

public static DateTime? fmtLST;
//or 
public static Nullable<DateTime> fmtLST; 

A nullable DateTime is most easily specified using the question mark syntax

Edit:

Console.WriteLine(fmtLST != null ? fmtLST.ToString("hh:mm:ss tt") : "");

Another one could be

if(fmtLST == DateTime.MinValue)
{
   //your date is "01/01/0001 12:00:00 AM"
}
like image 88
Mohit S Avatar answered Oct 22 '22 11:10

Mohit S