【问题标题】:How to convert a nullable datetime value to string.empty when datetime is null?当 datetime 为 null 时,如何将可为 null 的 datetime 值转换为 string.empty?
【发布时间】:2017-02-06 10:59:45
【问题描述】:

我正在读回一个可为空的 DateTime? 属性,然后将该值分配给短日期格式的字符串属性。

我可以将日期时间值转换为短日期字符串并分配给IT_Date_String 属性。但是如果IT_Date 为空,我不确定如何将"" 值分配给字符串。

如何转换日期时间?日期时间时 string.empty 的值?为空?

这是 linq 中的赋值:

var status_list = query_all.ToList().Select(r => new RelStatus
{
    IT_Date_String = r.IT_Date.Value.ToString("yyyy-MM-dd") != null ? r.IT_Date.Value : null
}).ToList();

以及模型中的属性:

public DateTime? IT_Date { get; set; }
public string IT_Date_String { get; set; }

【问题讨论】:

    标签: c# datetime nullable conditional-operator


    【解决方案1】:

    无论IT_Date 是否真的有值,您都在调用IT_Date.Value.ToString(...)

    所以你需要把表达式反过来:

    r.IT_Date.HasValue ? r.IT_Date.Value.ToString(...) : ""
    

    这样ToString() 只会在IT_Date 有值时被调用。

    您也可以在 getter 中实现这一点,如现在已删除的评论中所述:

    public string IT_Date_String 
    { 
        get
        {
            return IT_Date.HasValue ? IT_Date.Value.ToString(...) : "";
        }
    }
    

    这样您就不必在访问此模型的任何地方重新实现逻辑,并且作为奖励,它只会在实际请求时执行。

    还有no need to explicitly use String.Empty, the string "" will be interned to the same at runtime

    【讨论】:

    • 我喜欢将转换注入模型属性的想法。但是当我这样做时,作业告诉我IT_Date_String 是只读的。我还需要为该字符串属性添加一个设置器吗?
    • 喜欢:IT_Date_String = r.IT_Date 表示该作业是只读的。
    • 如果您希望能够通过将字符串分配给 IT_Date_String 属性来设置日期,那么是的,您还需要一个将字符串转换为 DateTime 并将其分配给 @ 987654333@财产。
    【解决方案2】:

    在 C# 6 中,您可以这样做:

    IT_Date_String = r.IT_Date?.ToString("yyyy-MM-dd") ?? String.Empty;
    

    新的? 检查左边的东西是否为空,如果是,则表达式计算为null。如果没有,它只是继续评估。

    然后,?? 检查第一个表达式的结果是否为null,如果IT_Date 为空则为空。如果是,则评估为String.Empty

    【讨论】:

      【解决方案3】:

      借助 C# 6.0 和 null 传播,您可以使用:

      IT_Date_String = r.IT_Date?.ToString("yyyy-MM-dd") ?? String.Empty
      

      【讨论】:

        【解决方案4】:

        这个可以在任何版本的框架中工作:

        IT_Date_String=string.Format("{0:yyyy-MM-dd}",IT_Date);
        

        【讨论】:

        • 没错,尽管yyyy-MM-dd 可能更有效,至少使用对日期/时间跟踪的常识理解。 :)
        • 感谢您指出这一点,我已经更正了我的答案。使用 CultureInfo 代替原始模式可能会更好,但这不在问题范围内
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-29
        • 1970-01-01
        • 2019-06-03
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多