![](/img/trans.png)
[英]DateTime XAML Binding String Format to show “null” for DateTime.MinValue
[英]DateTime To Be NULL when the value is DateTime.MinValue or it is Null
在我的控制台應用程序中,我正在嘗試格式化為HHmmss
- >我確定這是由於我的數據類型但是如何在NULL
時將其設為NULL
並且不顯示1/1/0001 12:00:00 AM
?
這是我的語法
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"));
如果改為public static DateTime? fmtLastScanTime;
public static DateTime? fmtLastScanTime;
我得到一個錯誤
'方法'ToString'沒有重載需要1個參數
如何將此顯示1/1/0001 12:00:00 AM
NULL
而不是1/1/0001 12:00:00 AM
? 試圖計算顯示的1/1/0001 12:00:00 AM
可以為空的DateTime。 可以為空的DateTime可以為null。 DateTime結構本身不提供null選項。 但是"DateTime?"
nullable類型允許您將null文本分配給DateTime類型。 它提供了另一層次的間接性。
public static DateTime? fmtLST;
//or
public static Nullable<DateTime> fmtLST;
使用問號語法最容易指定可為空的DateTime
編輯:
Console.WriteLine(fmtLST != null ? fmtLST.ToString("hh:mm:ss tt") : "");
另一個可能是
if(fmtLST == DateTime.MinValue)
{
//your date is "01/01/0001 12:00:00 AM"
}
我發現這個refrence 這里 seraching對於同樣的問題時,
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());
}
}
}
}
你可以進入鏈接查找更多詳情謝謝
值1/1/0001 12:00:00 AM
是DateTime對象的最小值/默認值,如果要為DateTime對象賦值null,則意味着必須將它們設置為Nullable
(與其他建議的一樣)。 所以fmtLST
的聲明應該是:
public static DateTime? fmtLST = null; // initialization is not necessary
在這種情況下,您必須關心將輸出打印到控制台。 它應該是這樣的:
Console.WriteLine(fmtLST.HasValue ? fmtLST.Value.ToString("hh:mm:ss tt") : "Value is null");
可能會嘗試這個
IFormatProvider format = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
fmtLST = DateTime.ParseExact((LST != null ? LST : null), "HHmmss", format);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.