开发者

c# DateTime convert to string

开发者 https://www.devze.com 2023-02-13 04:24 出处:网络
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 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 i开发者_如何学Pythonn";
                }


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!


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.


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.


You cant store a string into Datetime ! But you can do this

Datetime? Egresstime ;

DateTime timeOut;
if(!DateTime.TryParse(rdr["timeOut"], out timeOut))
{
    Egresstime  = null;
}
If(Egresstime ==null)
{
//print still logged in
}


You might be able to make it an object instead of a DateTime.

What I would do is make Egresstime a nullable DateTime (DateTime?) and set it to null.

if (Convert.IsDBNull(rdr["timeOut"]))
{
    queryResult.Egresstime = null;
}

Then right before I output it to my report/UI/whatever, I then check for null.

Egresstime.Text = queryResult.Egresstime == null ? "Still logged in" : Egresstime.ToString();
0

精彩评论

暂无评论...
验证码 换一张
取 消