Have datetime.now return to the nearest second

前端 未结 6 856
眼角桃花
眼角桃花 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 05:06

    Here is a rounding method that rounds up or down to the nearest second instead of just trimming:

    public static DateTime Round(this DateTime date, long ticks = TimeSpan.TicksPerSecond) {
        if (ticks>1)
        {
            var frac = date.Ticks % ticks;
            if (frac != 0)
            {
                // Rounding is needed..
                if (frac*2 >= ticks)
                {
                    // round up
                    return new DateTime(date.Ticks + ticks - frac);
                }
                else
                {
                    // round down
                    return new DateTime(date.Ticks - frac);
                }
            }
        }
        return date;
    }
    

    It can be used like this:

    DateTime now = DateTime.Now;
    DateTime nowTrimmedToSeconds = now.Round(TimeSpan.TicksPerSecond);
    DateTime nowTrimmedToMinutes = now.Round(TimeSpan.TicksPerMinute);
    

提交回复
热议问题