DateTime Round Up and Down

前端 未结 5 1861
面向向阳花
面向向阳花 2021-02-07 12:58

Ive been looking for a proper rounding mechanism but nothing I find seems to be exactly what I need.

I need to round up and round down seperately and I also need to acco

5条回答
  •  旧巷少年郎
    2021-02-07 13:46

    Another approach avoiding arithmetic using type long.

    Using integer division, where a & b are positive integers:

    a/b             // rounding down 
    (a+b-1)/b       // rounding up 
    ((2*a)+b)/(2*b) // rounding to the nearest (0.5 up)
    

    To round up:

    public static DateTime UpToNearestXmin( DateTime dt, int block )
    {
       int a = dt.Minute;
       int b = block;
    
       int mins = block * (( a + b - 1 ) / b );
    
       return new DateTime( dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0 ).AddMinutes( mins );
    }
    

    To round down or to nearest, change the mins calculation as appropriate.

    The minutes are rounded. The seconds & milliseconds are zeroed which is expected behaviour.

提交回复
热议问题