DateTime To NULL when DateTime.MinValue or Null

In my console application, I am trying to format to HHmmss - HHmmss I'm sure this is related to my data types, but how can I 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 changed to public static DateTime? fmtLastScanTime; public static DateTime? fmtLastScanTime; I get an error

'No overload for' ToString 'method takes 1 argument

How can I use this NULL screen instead of 1/1/0001 12:00:00 AM ? Trying to take readings 1/1/0001 12:00:00 AM

+5
source share
4 answers

Maybe, but try this

 IFormatProvider format = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat; fmtLST = DateTime.ParseExact((LST != null ? LST : null), "HHmmss", format); 
0
source

Nullable DateTime. A nullTime value with a null value may be null. The DateTime structure itself does not provide a null option. But the type is "DateTime?" nullable allows you to assign a null literal to the DateTime type. It provides another level of indirection.

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

Least DateTime is most easily specified using question mark syntax

Edit:

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

Another may be

 if(fmtLST == DateTime.MinValue) { //your date is "01/01/0001 12:00:00 AM" } 
+3
source

I found this refrence here when serializing for the same problem

 using System; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Nullable nullDateTime; //DateTime? nullDateTime = null; nullDateTime = DateTime.Now; if (nullDateTime != null) { MessageBox.Show(nullDateTime.Value.ToString()); } } } } 

you can find the link in more detail thanks

0
source

The value 1/1/0001 12:00:00 AM is the minimum / default value for a DateTime object, if you want to assign a null object to a DateTime object, then you must make them as Nullable (like other others). So the fmtLST should be:

 public static DateTime? fmtLST = null; // initialization is not necessary 

In this case, you should take care of printing the output to the console. it should be something like:

 Console.WriteLine(fmtLST.HasValue ? fmtLST.Value.ToString("hh:mm:ss tt") : "Value is null"); 
0
source

Source: https://habr.com/ru/post/1262622/


All Articles