有datetime.now返回最近的秒 [英] Have datetime.now return to the nearest second
问题描述
我有一个要求将时间戳记到最接近的秒数……但没有比这更准确的了。四舍五入或截断时间就可以了。
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.
我想出了这个可憎之物
dateTime = DateTime.Parse(DateTime.UtcNow.ToString("U"));
(U是长格式日期和时间。 2007年1月3日17:25:30)
(U is the Long format date and time. "03 January 2007 17:25:30")
是否有一些不太可怕的方法来实现这一目标?
Is there some less horrific way of achieving this?
编辑:因此,从链接的截短毫秒答案中(谢谢约翰·奥多姆(John Odom))
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.
推荐答案
您可以将其实现为扩展方法,使您可以将给定的DateTime调整为指定的精度。使用基础的标记:
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);
这篇关于有datetime.now返回最近的秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!