Have datetime.now return to the nearest second

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

    After working with the selected solution I am satisfied that it works well. However the implementations of the extension methods posted here do not offer any validation to ensure the ticks value you pass in is a valid ticks value. They also do not preserve the DateTimeKind of the DateTime object being truncated. (This has subtle but relevant side effects when storing to a database like MongoDB.)

    If the true goal is to truncate a DateTime to a specified value (i.e. Hours/Minutes/Seconds/MS) I recommend implementing this extension method in your code instead. It ensures that you can only truncate to a valid precision and it preserves the important DateTimeKind metadata of your original instance:

    public static DateTime Truncate(this DateTime dateTime, long ticks)
    {
        bool isValid = ticks == TimeSpan.TicksPerDay 
            || ticks == TimeSpan.TicksPerHour 
            || ticks == TimeSpan.TicksPerMinute 
            || ticks == TimeSpan.TicksPerSecond 
            || ticks == TimeSpan.TicksPerMillisecond;
    
        // https://stackoverflow.com/questions/21704604/have-datetime-now-return-to-the-nearest-second
        return isValid 
            ? DateTime.SpecifyKind(
                new DateTime(
                    dateTime.Ticks - (dateTime.Ticks % ticks)
                ),
                dateTime.Kind
            )
            : throw new ArgumentException("Invalid ticks value given. Only TimeSpan tick values are allowed.");
    }
    

    Then you can use the method like this:

    DateTime dateTime = DateTime.UtcNow.Truncate(TimeSpan.TicksPerMillisecond);
    
    dateTime.Kind => DateTimeKind.Utc
    

提交回复
热议问题