Loo*_*fer 12 c# datetime c#-4.0
我有一个"要求"给出最接近的第二个时间戳...但不是更准确.舍入或截断时间很好.
我想出了这种可憎的事
dateTime = DateTime.Parse(DateTime.UtcNow.ToString("U"));
Run Code Online (Sandbox Code Playgroud)
(U是长格式的日期和时间."2007年1月3日17:25:30")
是否有一些不那么可怕的方法来实现这一目标?
编辑:所以从链接截断毫秒回答(感谢约翰奥多姆)我将这样做
private static DateTime GetCurrentDateTimeNoMilliseconds()
{
var currentTime = DateTime.UtcNow;
return new DateTime(currentTime.Ticks - (currentTime.Ticks % TimeSpan.TicksPerSecond), currentTime.Kind);
}
Run Code Online (Sandbox Code Playgroud)
几乎不那么可怕..但它确实保留了我所关心的日期时间的"种类".我的解决方案没有.
Jes*_*ter 36
您可以将其实现为扩展方法,允许您使用基础Ticks将给定DateTime修剪为指定的精度:
public static DateTime Trim(this DateTime date, long ticks) {
return new DateTime(date.Ticks - (date.Ticks % ticks), date.Kind);
}
Run Code Online (Sandbox Code Playgroud)
然后很容易将你的日期修剪成各种精度:
DateTime now = DateTime.Now;
DateTime nowTrimmedToSeconds = now.Trim(TimeSpan.TicksPerSecond);
DateTime nowTrimmedToMinutes = now.Trim(TimeSpan.TicksPerMinute);
Run Code Online (Sandbox Code Playgroud)
您可以使用以下构造函数:
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second
)
Run Code Online (Sandbox Code Playgroud)
因此它将是:
DateTime dt = DateTime.Now;
DateTime secondsDt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
Run Code Online (Sandbox Code Playgroud)
如果你真的想把时间四舍五入到最接近的秒,你可以使用:
DateTime.MinValue
.AddSeconds(Math.Round((DateTime.Now - DateTime.MinValue).TotalSeconds));
Run Code Online (Sandbox Code Playgroud)
但是,除非额外的半秒真的有所作为,否则您可以删除毫秒部分:
DateTime.Now.AddTicks( -1 * (DateTime.Now.Ticks % TimeSpan.TicksPerSecond));
Run Code Online (Sandbox Code Playgroud)