Have datetime.now return to the nearest second

前端 未结 6 831
眼角桃花
眼角桃花 2021-01-04 04:38

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 t

6条回答
  •  悲&欢浪女
    2021-01-04 04:49

    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));
    

提交回复
热议问题