C# DateTime 转换为字符串
我有一个结果集,其中一些时间存储在 DateTime 变量中。如果该值为空,我想将 var 设置为字符串“仍然登录”。
我尝试过一些 toString() 的东西,但还没有运气。
这是不起作用的代码。 queryResult.Egresstime 是 DateTime 类型,不能是字符串。
if (Convert.IsDBNull(rdr["timeOut"]))
{
queryResult.Egresstime = "Still logged in";
}
I have a result set with some times stored in DateTime variables. If the value is null I want to set the var to the string "Still logged in".
I've tried some toString() things but had no luck yet.
This is the code that doesn't work. queryResult.Egresstime is type DateTime and can't be a string.
if (Convert.IsDBNull(rdr["timeOut"]))
{
queryResult.Egresstime = "Still logged in";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这似乎是设计上的缺陷,但如果您绝对必须像这样保留它,您可以将其设置为过去的一个可笑的精确日期,并在渲染日期之前检查以渲染“仍然登录”(如果是该特定日期)。但这是一种糟糕的设计方式!
That seems like a flaw in design but if you absolutely must keep it like this, you could set it to a precise date ridiculously far in the past and check before rendering the date to render "Still logged in" if it's that particular date. That is a terrible way to design things though!
您在这里运气不佳 - 您无法将字符串分配给
DateTime
类型的属性。事实并非如此。You are out of luck here - you can't assign a string to a property of type
DateTime
. It simply doesn't work that way.您不能将字符串分配给日期时间。
也许您需要另一个字段来指示时间是否有效,如果无效,则显示“仍然登录”文本?
如果您能够将 EgressTime 更改为可为 null 的 DateTime (
DateTime?
),则可以使用 null 来指示该值不存在。You can't assign a string to a DateTime.
Perhaps you need to have another field indicating whether the time is valid, and if not, display the "Still logged in" text instead ?
If you are able to change EgressTime to be a nullable DateTime (
DateTime?
), you could use null to indicate that the value doesn't exist.您无法将字符串存储到 Datetime 中!
但你可以这样做
You cant store a string into Datetime !
But you can do this
您也许可以将其设为
对象
,而不是DateTime
。我要做的是将 Egresstime 设置为可为 null 的 DateTime (
DateTime?
) 并将其设置为null
。然后,在将其输出到我的报告/UI/其他内容之前,我检查是否为空。
You might be able to make it an
object
instead of aDateTime
.What I would do is make Egresstime a nullable DateTime (
DateTime?
) and set it tonull
.Then right before I output it to my report/UI/whatever, I then check for null.