如何将DateTime设置为null [英] How to set DateTime to null

查看:249
本文介绍了如何将DateTime设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#。我有一个字符串 dateTimeEnd

Using C#. I have a string dateTimeEnd.

如果该字符串格式正确,我希望生成一个 DateTime 并将其分配给type的eventCustom.DateTimeEnd

If the string is in right format, I wish to generate a DateTime and assign it to eventCustom.DateTimeEnd of type

public Nullable<System.DateTime> DateTimeEnd { get; set; }

如果 dateTimeEnd 为空或为空,我需要将 eventCustom.DateTimeEnd 设置为null。

If dateTimeEnd is null or empty I need eventCustom.DateTimeEnd set to null.

我正在尝试使用以下代码来实现,但我总是 eventCustom.DateTimeEnd 为空。

I am trying to achieve this using the following code but I get always null for eventCustom.DateTimeEnd.

请帮助我定义代码中的错误吗?

Could you please help me out to define what is wrong in my code?

   DateTime? dateTimeEndResult;
     if (!string.IsNullOrWhiteSpace(dateTimeEnd))
        dateTimeEndResult = DateTime.Parse(dateTimeEnd);


eventCustom.DateTimeEnd = dateTimeEndResult = true ? (DateTime?)null : dateTimeEndResult;


推荐答案

您似乎只是想要:

eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
    ? (DateTime?) null
    : DateTime.Parse(dateTimeEnd);

请注意,如果 dateTimeEnd 不是有效日期。

Note that this will throw an exception if dateTimeEnd isn't a valid date.

另一种选择是:

DateTime validValue;
eventCustom.DateTimeEnd = DateTime.TryParse(dateTimeEnd, out validValue)
    ? validValue
    : (DateTime?) null;

现在将结果设置为 null 如果 dateTimeEnd 无效。请注意, TryParse 可以将 null 当作输入来处理。

That will now set the result to null if dateTimeEnd isn't valid. Note that TryParse handles null as an input with no problems.

这篇关于如何将DateTime设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆