Home > Software engineering >  Combine two datetime variables into one
Combine two datetime variables into one

Time:10-27

sorry for my noob question in advance i have two datetime variables i want to combine them together ..

this is the normal code that i have

Int32 addDay = Convert.ToInt32((ucWait.model.SelectMCCodeAskOutObj as SelectMCCodeAsk_OUT).PRIORITY);
this.dp_RST.SelectedDate = CommonServiceAgent.SelectSysDate().AddDays(addDay);

it is reading from sysdate, i'm trying to change it to read from another variable this is my attempt of the doing so :

Int32 addDay = Convert.ToInt32((mcnon.model.SelectMCCodeAskOutObj as SelectMCCodeAsk_OUT).PRIORITY);
this.dp_RST.SelectedDate = (dgFUList.SelectedItem as SelOutOrderInfo_OUT).NEXT_DAY.AddDays(addDay);

the error it gives that the AddDays not define

(System.Nullable<System.datetime> dose not contain a definition for 'AddDays' and no extension method 'AddDays' accepting a first argument of type 'System.Nullable<System.datetime>' could be found (are you missing a using directive or an assembly reference? ) )

CodePudding user response:

It seems that SelOutOrderInfo_OUT.NEXT_DAY is of type Nullable<DateTime> (DateTieme? is syntactic sugar for the same) and Nullable<DateTime> doesn't contain a method AddDays()

You should first verify that .NEXT_DAY doesn't return a null value and then call AddDays() on the underlying value.

Depending on the version of C# you are using you should be able to do

this.dp_RST.SelectedDate = (dgFUList.SelectedItem as SelOutOrderInfo_OUT).NEXT_DAY
    .Value? // Check for null before attempting to add days.
    .AddDays(addDay);

CodePudding user response:

The error clearly states that it's coming on this line.

this.dp_RST.SelectedDate = (dgFUList.SelectedItem as SelOutOrderInfo_OUT).NEXT_DAY.AddDays(addDay);

This is because NEXT_DAY Property in SelOutOrderInfo_OUT Type is Nullable<DateTime>.

You can do

this.dp_RST.SelectedDate = (dgFUList.SelectedItem as SelOutOrderInfo_OUT).NEXT_DAY.Value.AddDays(addDay);

However, you can check if the value is not blank otherwise you can run into issues.

Better Solution

var dt = (dgFUList.SelectedItem as SelOutOrderInfo_OUT).NEXT_DAY;

if (dt.HasValue)
    this.dp_RST.SelectedDate = dt.Value.AddDays(addDay);
  •  Tags:  
  • c#
  • Related