Datetime in C# add days
DateTime is immutable. That means you cannot change it's state and have to assign the result of an operation to a variable.
endDate = endDate.AddDays(addedDays);
Adding days to a DateTime in C#
Do you want to add days?
DateTime newDate = DateTime.Today.AddDays(10);
Note that you get a new DateTime back!
MSDN
C# Datetime add days with hours and minutes
Use DateTime.Now
instead of DateTime.Today
DateTime.Now
is not dirty, and formatting it is not either
DateTime.Now
gives you a DateTime variable.
The formatting .ToString()
returns a string to format as you wish.
How can I add a day to a DateTime in a specific timezone
Here are extension methods that you can use for this.
First, this AddDays
method matches the signature you were asking about. It operates on DateTime
values:
public static DateTime AddDays(this DateTime dt, double days, TimeZoneInfo tz)
{
// If the kind is Local or Utc, convert that point in time to the given time zone
DateTimeKind originalKind = dt.Kind;
if (originalKind != DateTimeKind.Unspecified)
{
dt = TimeZoneInfo.ConvertTime(dt, tz);
}
// Add days with respect to the wall time only
DateTime added = dt.AddDays(days);
// Resolve the added value to a specific point in time
DateTimeOffset resolved = added.ToDateTimeOffset(tz);
// Return only the DateTime portion, but take the original kind into account
switch (originalKind)
{
case DateTimeKind.Local:
return resolved.LocalDateTime;
case DateTimeKind.Utc:
return resolved.UtcDateTime;
default: // DateTimeKind.Unspecified
return resolved.DateTime;
}
}
Here is another variation of that extension method. This one operates on DateTimeOffset
values:
public static DateTimeOffset AddDays(this DateTimeOffset dto, double days, TimeZoneInfo tz)
{
// Make sure the input time is in the provided time zone
dto = TimeZoneInfo.ConvertTime(dto, tz);
// Add days with respect to the wall time only
DateTime added = dto.DateTime.AddDays(days);
// Resolve the added value to a specific point in time
DateTimeOffset resolved = added.ToDateTimeOffset(tz);
// Return the fully resolved value
return resolved;
}
Both of the above methods depend on the following ToDateTimeOffset
extension method (which I've used in a few different posts now).
public static DateTimeOffset ToDateTimeOffset(this DateTime dt, TimeZoneInfo tz)
{
if (dt.Kind != DateTimeKind.Unspecified)
{
// Handle UTC or Local kinds (regular and hidden 4th kind)
DateTimeOffset dto = new DateTimeOffset(dt.ToUniversalTime(), TimeSpan.Zero);
return TimeZoneInfo.ConvertTime(dto, tz);
}
if (tz.IsAmbiguousTime(dt))
{
// Prefer the daylight offset, because it comes first sequentially (1:30 ET becomes 1:30 EDT)
TimeSpan[] offsets = tz.GetAmbiguousTimeOffsets(dt);
TimeSpan offset = offsets[0] > offsets[1] ? offsets[0] : offsets[1];
return new DateTimeOffset(dt, offset);
}
if (tz.IsInvalidTime(dt))
{
// Advance by the gap, and return with the daylight offset (2:30 ET becomes 3:30 EDT)
TimeSpan[] offsets = { tz.GetUtcOffset(dt.AddDays(-1)), tz.GetUtcOffset(dt.AddDays(1)) };
TimeSpan gap = offsets[1] - offsets[0];
return new DateTimeOffset(dt.Add(gap), offsets[1]);
}
// Simple case
return new DateTimeOffset(dt, tz.GetUtcOffset(dt));
}
Lastly, I'll point out that there is another option to consider: Use the Noda Time library. It's ZoneDateTime.Add
method has exactly this purpose.
How to add day to DateTime at end of month?
var ldUserEndTime = DateTime.Today + new TimeSpan(1, 0, 45, 0);
How to add days to a date and pass the sum to an inputdate in c #?
The following code snippet contains two InputDate components. When you select a date in the first one, the date in the second one changed to the selected date in the first component plus 45 days.
@page "/"
<EditForm EditContext="EditContext" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
<InputDate placeholder="Arrival Date" @bind-Value="person.ArrivalDate"
@oninput="AddDays" />
<InputDate placeholder="Departure Date" @bind-Value="person.DepartureDate" />
<ValidationMessage For="@(() => person.ArrivalDate)" />
<ValidationMessage For="@(() => person.DepartureDate)" />
<p><button type="submit">Submit</button></p>
</EditForm>
@code {
private Person person = new Person();
EditContext EditContext;
protected override void OnInitialized()
{
EditContext = new EditContext(person);
base.OnInitialized();
}
private async Task AddDays(ChangeEventArgs args)
{
person.DepartureDate = Convert.ToDateTime(args.Value).AddDays(45);
await Task.CompletedTask;
}
void HandleValidSubmit()
{
Console.WriteLine("TODO: Actually do something with the valid data");
}
public class Person
{
public DateTime ArrivalDate { get; set; } = DateTime.Now;
public DateTime DepartureDate { get; set; } = DateTime.Now;
}
}
Hope this helps...
DateTime.AddDays what value to pass to generate an exception
If you pass in int.MaxValue
, that should end up with a value which is outside the representable range for DateTime
, whatever the original DateTime
is.
Sample code, tested on csharppad.com:
DateTime.MinValue.AddDays(int.MaxValue);
Using Assert.Fail
in a finally
block is a mistake though... that will always be called. It's not clear what your test framework is, but I'd expect something like:
Assert.Throws<ArgumentOutOfRangeException>(() => /* code here */);
Related Topics
Get Substring - Everything Before Certain Char
Problems Using Entity Framework 6 and SQLite
How to Generate a Unique Token Which Expires After 24 Hours
Wcf Gives an Unsecured or Incorrectly Secured Fault Error
Receiving JSON Data Back from Http Request
Where to Find "Microsoft.Visualstudio.Testtools.Unittesting" Missing Dll
Resharper Conventions for Names of Event Handlers
How to Make a Wizard with ASP.NET MVC
Learning Single Responsibility Principle with C#
Getmanifestresourcestream Returns Null
Conditionally Required Property Using Data Annotations
Getting Current Directory in .Net Web Application
How Can a Wpf Usercontrol Inherit a Wpf Usercontrol
What's the Difference Setting Embed Interop Types True and False in Visual Studio
Give Some Command to View in Mvvm
How to Determine the Length (I.E. Duration) of a .Wav File in C#