Have datetime.now return to the nearest second

前端 未结 6 725
眼角桃花
眼角桃花 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:08

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

提交回复
热议问题