📜  c# datetime remove days - C# (1)

📅  最后修改于: 2023-12-03 15:13:48.739000             🧑  作者: Mango

C# DateTime Remove Days

In C#, DateTime is a value type that represents date and time values.

If you want to remove days from a DateTime object, you can use the DateTime.AddDays method:

DateTime date = DateTime.Now;
int daysToRemove = 7;
DateTime newDate = date.AddDays(-daysToRemove);
Console.WriteLine(newDate);

This code will subtract 7 days from the current date and time (DateTime.Now) and store the result in newDate. The result will be displayed in the console.

If you want to remove a certain number of days from a DateTime object, you can subtract that number of days using a TimeSpan object:

DateTime date = DateTime.Now;
int daysToRemove = 7;
TimeSpan timeSpan = new TimeSpan(daysToRemove, 0, 0, 0);
DateTime newDate = date - timeSpan;
Console.WriteLine(newDate);

This code will accomplish the same thing as the previous example, but it uses a TimeSpan object to represent the number of days to remove.

You can also use the DateTime.Subtract method with a TimeSpan object:

DateTime date = DateTime.Now;
int daysToRemove = 7;
TimeSpan timeSpan = new TimeSpan(daysToRemove, 0, 0, 0);
DateTime newDate = date.Subtract(timeSpan);
Console.WriteLine(newDate);

This code will also remove 7 days from the current date and time, but it uses the DateTime.Subtract method instead of the - operator.

These methods allow you to remove days from a DateTime object in C#.