Ali Kazemi Ali Kazemi - 22 days ago 8
C# Question

Unity C#, How to addition X days to a date?

In this part of code sDate show current date 2016/11/16, Now what is best way to add 7 days to current date? for example if current date is 2016/11/29 + 7 change to 2016/12/06. I'm looking for a way to addition an int value to a date.

string Year;
string Month;
string Day;
float time;
string sDate;

void Start ()
{

Year = System.DateTime.Now.Year.ToString();
Month = System.DateTime.Now.Month.ToString();
Day = System.DateTime.Now.Day.ToString();

int Y = int.Parse (Year);
int M = int.Parse (Month);
int D = int.Parse (Day);


if (Y >= 2016 & M >= 11 & D >= 21)
{
sDate = Year + "/" + Month + "/" + Day + " | Expired";
Debug.Log (sDate);

Application.Quit ();
}
else
{
sDate = Year + "/" + Month + "/" + Day + " | Working";
Debug.Log ("System date: " + sDate);
}

}

Answer

All you need to do is use the standard DateTime function AddDays:

DateTime result = original.AddDays(n);

where original is the original date and n is the number of days you want to add.

I'd also check the rest of the documentation on the DateTime structure as there are a lot simpler ways of doing what you are trying here. As mentioned in the comments you can construct a DateTime object from it's components:

DateTime referenceDate = new DateTime(2016, 11, 15);

and then do comparisons on that:

if (testDate >= referenceDate)
{
    // Do something
}

etc.