Have datetime.now return to the nearest second
You can use this constructor:
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second
)
so it would be:
DateTime dt = DateTime.Now;
DateTime secondsDt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
If you really want to round the time to the nearest second, you can use:
DateTime.MinValue
.AddSeconds(Math.Round((DateTime.Now - DateTime.MinValue).TotalSeconds));
However unless that extra half a second really makes a difference, you can just remove the millisecond portion:
DateTime.Now.AddTicks( -1 * (DateTime.Now.Ticks % TimeSpan.TicksPerSecond));
You could implement this as an extension method that allows you to trim a given DateTime to a specified accuracy using the underlying Ticks:
public static DateTime Trim(this DateTime date, long ticks) {
return new DateTime(date.Ticks - (date.Ticks % ticks), date.Kind);
}
Then it is easy to trim your date to all kinds of accuracies like so:
DateTime now = DateTime.Now;
DateTime nowTrimmedToSeconds = now.Trim(TimeSpan.TicksPerSecond);
DateTime nowTrimmedToMinutes = now.Trim(TimeSpan.TicksPerMinute);