开发者

Datetime? to string

I need to convert a Datetime? to a string. The ?? operator dosent work and calling tostring on a null would make things fall over. Any advice on how to handle datetime? Thanks

Below is my code for context. o.CustomerRequiredDate is a Datetime? and PredictedActivationDate is a string. Both need to stay as the datatype they currently are.

 {
       rsp = (from r in db.btRequests
                                      join o in db.NewOrders
                                      on r.ID equals o.RequestId
                                      join s in db.Status
                                      on r.Status equals s.ID.ToString()
                                      select new DataLayer.OrderResponse
                                      {
                                          RequestID = requestID,
                                          Message = s.StatusDescription,
                                          OrderStatus = r.Status.ToString(),
                                          PredictedActivationDate =r.Status == "3" || r.Status == "4" || r.Status == "5"
                                  开发者_开发技巧        || r.Status == "6" || r.Status == "9" ? (o.CustomerRequiredDate ?? ""): ""

                                      }).FirstOrDefault();


You could do

o.CustomerRequiredDate.HasValue ? o.CustomerRequiredDate.Value.ToString() : ""


o.CustomerRequiredDate.ToString()

It returns an empty string for a DateTime? with a null value and the DateTime.ToString otherwise.


I'm assuming o.CustomerRequiredDate is your DateTime?.

Try

o.CustomerRequiredDate.HasValue ? o.CustomerRequiredDate.ToString() : string.Empty

instead.


o.CustomerRequiredDate.HasValue ? o.CustomerRequiredDate.Value.ToString() : string.Empty


Outside of SQL for moment, Nullable<T>.ToString() is documented to return an empty string if HasValue is false (ie., it "is null").

If you are concerned that the statements

DateTime? date = null;
string output = date.ToString(); 

will "fall over," fear not. Of course, if using the expression in Linq, it would be up to the provider (-to-SQL, -to-EF), to behave properly.


A nullable value is never null in the sense that you can't use ToString on it:

o.CustomerRequiredDate.ToString()

However, you might want a different result than the default empty string for a null value:

o.CustomerRequiredDate.HasValue ? o.CustomerRequiredDate.Value.ToString() : "No date"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜