您是否尝试过类似以下的方法?我已经成功地使用了类似的方法来四舍五入到下一个小时、分钟、天等......
private static readonly long _ticksIn30Mins = TimeSpan.FromMinutes(30).Ticks;
protected DateTime GetRoundedTime(DateTime inputTime)
{
long currentTicks = inputTime.Ticks;
return new DateTime(currentTicks.RoundUp(_ticksIn30Mins));
}
public static class ExtensionMethods
{
public static long RoundUp(this long i, long toTicks)
{
return (long)(Math.Round(i / (double)toTicks,
MidpointRounding.AwayFromZero)) * toTicks;
}
}
这采用上一个问题中的 RoundOff 方法。您只需使用 MidpointRoundingMode.AwayFromZero 将其修改为始终向上取整。
最后,为了应对上午 12:00 变为上午 12:30 的具体情况,然后检查您的舍入前后值是否相同,如果是,则增加刻度的汇总量(例如 30 分钟)
var currentTime = DateTime.Now;
var rounded = GetRoundedTime(currentTime);
if (rounded == currentTime)
{
rounded = new DateTime(rounded.Ticks + _ticksIn30Mins);
}
对于演示此原理的经过测试的控制台应用程序,请参见以下内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
private static readonly long _ticksIn30Mins = TimeSpan.FromMinutes(30).Ticks;
static void Main(string[] args)
{
WriteDateString(new DateTime(2012, 01, 18, 09, 45, 11, 152));
WriteDateString(new DateTime(2012, 01, 18, 12, 15, 11, 999));
WriteDateString(new DateTime(2012, 01, 18, 12, 00, 00, 000));
Console.ReadLine();
}
private static void WriteDateString(DateTime dateTime)
{
Console.WriteLine("Before: {0}, After: {1}", dateTime, GetRoundedTime(dateTime));
}
private static DateTime GetRoundedTime(DateTime inputTime)
{
long currentTicks = inputTime.Ticks;
var rounded = new DateTime(currentTicks.RoundUp(_ticksIn30Mins));
if (rounded == inputTime)
{
rounded = new DateTime(rounded.Ticks + _ticksIn30Mins);
}
return rounded;
}
}
public static class ExtensionMethods
{
public static long RoundUp(this long i, long toTicks)
{
return (long)(Math.Round(i / (double)toTicks, MidpointRounding.AwayFromZero)) * toTicks;
}
}
}
输出:
最好的祝福,