C# Nullable<DateTime> 到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1445766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:36:04  来源:igfitidea点击:

C# Nullable<DateTime> to string

c#datetime

提问by JL.

I have a DateTime?variable, sometimes the value is null, how can I return an empty string ""when the value is nullor the DateTimevalue when not null?

我有一个DateTime?变量,有时值null,我怎么能返回一个空字符串""当值nullDateTime值时不null

采纳答案by Jon Seigel

string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;

回答by Ahmed Khalaf

DateTime? MyNullableDT;
....
if (MyNullableDT.HasValue)
{
    return MyNullableDT.Value.ToString();
}
return "";

回答by Cecil Has a Name

DateTime? d;
// stuff manipulating d;
return d != null ? d.Value.ToString() : String.Empty;

回答by Mike

if (aDate.HasValue)
    return aDate;
else
    return string.Empty;

回答by Patrick Desjardins

DateTime d?;
string s = d.HasValue ? d.ToString() : string.Empty;

回答by JaredPar

You could write an extension method

你可以写一个扩展方法

public static string ToStringSafe(this DateTime? t) {
  return t.HasValue ? t.Value.ToString() : String.Empty;
}

...
var str = myVariable.ToStringSafe();

回答by Joey

Actually, this is the default behaviour for Nullable types, that without a value they return nothing:

实际上,这是 Nullable 类型的默认行为,如果没有值,它们将不返回任何内容:

public class Test {
    public static void Main() {
        System.DateTime? dt = null;
        System.Console.WriteLine("<{0}>", dt.ToString());
        dt = System.DateTime.Now;
        System.Console.WriteLine("<{0}>", dt.ToString());
    }
}

this yields

这产生

<>
<2009-09-18 19:16:09>

回答by Eric Lippert

Though many of these answers are correct, all of them are needlessly complex. The result of calling ToString on a nullable DateTime is already an empty string if the value is logically null.Just call ToString on your value; it will do exactly what you want.

尽管这些答案中有许多是正确的,但它们都不必要地复杂。如果值在逻辑上为空,则在可为空的 DateTime 上调用 ToString 的结果已经是空字符串。只需在您的值上调用 ToString ;它会做你想要的。

回答by DJ.

Calling .ToString()on a Nullable<T>that is nullwill return an empty string.

调用.ToString()a Nullable<T>that isnull将返回一个空字符串。

回答by Jalal

All you need to do is to just simply call .ToString(). It handles Nullable<T>object for nullvalue.

您需要做的只是简单地调用.ToString(). 它处理Nullable<T>对象的null价值。

Here is the source of .NET Frameworkfor Nullable<T>.ToString():

这里是.NET框架的来源Nullable<T>.ToString()

public override string ToString() {
    return hasValue ? value.ToString() : "";
}