I have a "requirement" to give a timestamp to the nearest second... but NOT more accurate than that. Rounding or truncating the time is fine.
I have come up with this abomination
dateTime = DateTime.Parse(DateTime.UtcNow.ToString("U"));
(U is the Long format date and time. "03 January 2007 17:25:30")
Is there some less horrific way of achieving this?
Edit: So from the linked truncate milliseconds answer (thanks John Odom) I am going to do this
private static DateTime GetCurrentDateTimeNoMilliseconds()
{
var currentTime = DateTime.UtcNow;
return new DateTime(currentTime.Ticks - (currentTime.Ticks % TimeSpan.TicksPerSecond), currentTime.Kind);
}
barely less horrific.. but it does preserve the 'kind' of datetime which I do care about. My solution did not.
To round the Timedelta with specified resolution, use the timestamp. round() method. Set the seconds frequency resolution using the freq parameter with value 's'.
The Now property returns a DateTime value that represents the current date and time on the local computer.
The ( + d. Ticks - 1) makes sure it will round up if necessary. The / and * are rounding.
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);
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With