Alright I'm diving in with my suggestion, an extension method:
public static DateTime ChangeTime(this DateTime dateTime, int hours, int minutes, int seconds, int milliseconds)
{
return new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
hours,
minutes,
seconds,
milliseconds,
dateTime.Kind);
}
Since DateTime is immutable, a new instance has to be created when a date component needs to be changed. Unfortunately, there is no built-in functionality to set individual components of a DateTime instance.
Using the following extension methods
public static DateTime SetPart(this DateTime dateTime, int? year, int? month, int? day, int? hour, int? minute, int? second)
{
return new DateTime(
year ?? dateTime.Year,
month ?? dateTime.Month,
day ?? dateTime.Day,
hour ?? dateTime.Hour,
minute ?? dateTime.Minute,
second ?? dateTime.Second
);
}
public static DateTime SetYear(this DateTime dateTime, int year)
{
return dateTime.SetPart(year, null, null, null, null, null);
}
public static DateTime SetMonth(this DateTime dateTime, int month)
{
return dateTime.SetPart(null, month, null, null, null, null);
}
public static DateTime SetDay(this DateTime dateTime, int day)
{
return dateTime.SetPart(null, null, day, null, null, null);
}
public static DateTime SetHour(this DateTime dateTime, int hour)
{
return dateTime.SetPart(null, null, null, hour, null, null);
}
public static DateTime SetMinute(this DateTime dateTime, int minute)
{
return dateTime.SetPart(null, null, null, null, minute, null);
}
public static DateTime SetSecond(this DateTime dateTime, int second)
{
return dateTime.SetPart(null, null, null, null, null, second);
}
Alright I'm diving in with my suggestion, an extension method:
Then call:
It's important to note that this extension returns a new date object, so you can't do this:
But you can do this:
Since
DateTime
is immutable, a new instance has to be created when a date component needs to be changed. Unfortunately, there is no built-in functionality to set individual components of aDateTime
instance.Using the following extension methods
you can set individual
DateTime
components likeWhat's wrong with DateTime.AddSeconds method where you can add or substract seconds?
I prefer this:
Use like this:
Console.WriteLine (DateTime.Now.ClearTimeFrom(eTimeFragment.hours))
this has to return: 2016-06-06 00:00:00.000
here is a ghetto way, but it works :)