2

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();
Tom Squires
  • 8,848
  • 12
  • 46
  • 72

6 Answers6

7

You could do

o.CustomerRequiredDate.HasValue ? o.CustomerRequiredDate.Value.ToString() : ""
Yuck
  • 49,664
  • 13
  • 105
  • 135
6
o.CustomerRequiredDate.ToString()

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

Guillaume
  • 12,824
  • 3
  • 40
  • 48
3

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

Try

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

instead.

CassOnMars
  • 6,153
  • 2
  • 32
  • 47
3
o.CustomerRequiredDate.HasValue ? o.CustomerRequiredDate.Value.ToString() : string.Empty
Berial
  • 557
  • 1
  • 8
  • 23
2

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.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
1

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"
Guffa
  • 687,336
  • 108
  • 737
  • 1,005