是否有一个简单的功能可以将 UP a DateTime
四舍五入到最近的15分钟?
E.g。
2011-08-11 16:59
变为2011-08-11 17:00
2011-08-11 17:00
保持为2011-08-11 17:00
2011-08-11 17:01
变为2011-08-11 17:15
答案 0 :(得分:247)
DateTime RoundUp(DateTime dt, TimeSpan d)
{
return new DateTime((dt.Ticks + d.Ticks - 1) / d.Ticks * d.Ticks, dt.Kind);
}
示例:的
var dt1 = RoundUp(DateTime.Parse("2011-08-11 16:59"), TimeSpan.FromMinutes(15));
// dt1 == {11/08/2011 17:00:00}
var dt2 = RoundUp(DateTime.Parse("2011-08-11 17:00"), TimeSpan.FromMinutes(15));
// dt2 == {11/08/2011 17:00:00}
var dt3 = RoundUp(DateTime.Parse("2011-08-11 17:01"), TimeSpan.FromMinutes(15));
// dt3 == {11/08/2011 17:15:00}
答案 1 :(得分:87)
提出的解决方案不涉及乘以和划分 long
数字。
public static DateTime RoundUp(this DateTime dt, TimeSpan d)
{
var modTicks = dt.Ticks % d.Ticks;
var delta = modTicks != 0 ? d.Ticks - modTicks : 0;
return new DateTime(dt.Ticks + delta, dt.Kind);
}
public static DateTime RoundDown(this DateTime dt, TimeSpan d)
{
var delta = dt.Ticks % d.Ticks;
return new DateTime(dt.Ticks - delta, dt.Kind);
}
public static DateTime RoundToNearest(this DateTime dt, TimeSpan d)
{
var delta = dt.Ticks % d.Ticks;
bool roundUp = delta > d.Ticks / 2;
var offset = roundUp ? d.Ticks : 0;
return new DateTime(dt.Ticks + offset - delta, dt.Kind);
}
用法:
var date = new DateTime(2010, 02, 05, 10, 35, 25, 450); // 2010/02/05 10:35:25
var roundedUp = date.RoundUp(TimeSpan.FromMinutes(15)); // 2010/02/05 10:45:00
var roundedDown = date.RoundDown(TimeSpan.FromMinutes(15)); // 2010/02/05 10:30:00
var roundedToNearest = date.RoundToNearest(TimeSpan.FromMinutes(15)); // 2010/02/05 10:30:00
答案 2 :(得分:18)
如果你需要舍入到最近的时间间隔(不是) 那么我建议使用以下
static DateTime RoundToNearestInterval(DateTime dt, TimeSpan d)
{
int f=0;
double m = (double)(dt.Ticks % d.Ticks) / d.Ticks;
if (m >= 0.5)
f=1;
return new DateTime(((dt.Ticks/ d.Ticks)+f) * d.Ticks);
}
答案 3 :(得分:8)
void Main()
{
var date1 = new DateTime(2011, 8, 11, 16, 59, 00);
date1.Round15().Dump();
var date2 = new DateTime(2011, 8, 11, 17, 00, 02);
date2.Round15().Dump();
var date3 = new DateTime(2011, 8, 11, 17, 01, 23);
date3.Round15().Dump();
var date4 = new DateTime(2011, 8, 11, 17, 00, 00);
date4.Round15().Dump();
}
public static class Extentions
{
public static DateTime Round15(this DateTime value)
{
var ticksIn15Mins = TimeSpan.FromMinutes(15).Ticks;
return (value.Ticks % ticksIn15Mins == 0) ? value : new DateTime((value.Ticks / ticksIn15Mins + 1) * ticksIn15Mins);
}
}
结果:
8/11/2011 5:00:00 PM
8/11/2011 5:15:00 PM
8/11/2011 5:15:00 PM
8/11/2011 5:00:00 PM
答案 4 :(得分:4)
由于我讨厌重新发明轮子,我可能会遵循这个算法将DateTime值四舍五入到指定的时间增量(Timespan):
DateTime
值转换为表示TimeSpan
单位的整数和小数的十进制浮点值。Math.Round()
将其舍入为整数。TimeSpan
单位中的刻度数来缩放回刻度。DateTime
值并将其返回给调用者。以下是代码:
public static class DateTimeExtensions
{
public static DateTime Round( this DateTime value , TimeSpan unit )
{
return Round( value , unit , default(MidpointRounding) ) ;
}
public static DateTime Round( this DateTime value , TimeSpan unit , MidpointRounding style )
{
if ( unit <= TimeSpan.Zero ) throw new ArgumentOutOfRangeException("unit" , "value must be positive") ;
Decimal units = (decimal) value.Ticks / (decimal) unit.Ticks ;
Decimal roundedUnits = Math.Round( units , style ) ;
long roundedTicks = (long) roundedUnits * unit.Ticks ;
DateTime instance = new DateTime( roundedTicks ) ;
return instance ;
}
}
答案 5 :(得分:2)
我的版本
DateTime newDateTimeObject = oldDateTimeObject.AddMinutes(15 - oldDateTimeObject.Minute % 15);
作为一种方法,它会像这样
public static DateTime GetNextQuarterHour(DateTime oldDateTimeObject)
{
return oldDateTimeObject.AddMinutes(15 - oldDateTimeObject.Minute % 15);
}
被这样称呼
DateTime thisIsNow = DateTime.Now;
DateTime nextQuarterHour = GetNextQuarterHour(thisIsNow);
答案 6 :(得分:1)
优雅?
dt.AddSeconds(900 - (x.Minute * 60 + x.Second) % 900)
答案 7 :(得分:1)
警告:上面的公式不正确,即以下内容:
DateTime RoundUp(DateTime dt, TimeSpan d)
{
return new DateTime(((dt.Ticks + d.Ticks - 1) / d.Ticks) * d.Ticks);
}
应改写为:
DateTime RoundUp(DateTime dt, TimeSpan d)
{
return new DateTime(((dt.Ticks + d.Ticks/2) / d.Ticks) * d.Ticks);
}
答案 8 :(得分:1)
更详细的解决方案,它使用模数并避免不必要的计算。
public static class DateTimeExtensions
{
public static DateTime RoundUp(this DateTime dt, TimeSpan ts)
{
return Round(dt, ts, true);
}
public static DateTime RoundDown(this DateTime dt, TimeSpan ts)
{
return Round(dt, ts, false);
}
private static DateTime Round(DateTime dt, TimeSpan ts, bool up)
{
var remainder = dt.Ticks % ts.Ticks;
if (remainder == 0)
{
return dt;
}
long delta;
if (up)
{
delta = ts.Ticks - remainder;
}
else
{
delta = -remainder;
}
return dt.AddTicks(delta);
}
}
答案 9 :(得分:0)
这是一个简单的解决方案,可以最接近1分钟。它保留DateTime的TimeZone和Kind信息。它可以进一步修改以满足您自己的需要(如果您需要舍入到最近的5分钟等)。
try humidity = int(humidity):
if humidity>75:
subList[2]="high"
else:
subList[2]="low"
except:
return 'bad values in file - humidity is not a number'
答案 10 :(得分:0)
您可以使用此方法,它使用指定的日期来确保它维护以前在datetime对象中指定的任何全球化和日期时间类型。
const long LNG_OneMinuteInTicks = 600000000;
/// <summary>
/// Round the datetime to the nearest minute
/// </summary>
/// <param name = "dateTime"></param>
/// <param name = "numberMinutes">The number minute use to round the time to</param>
/// <returns></returns>
public static DateTime Round(DateTime dateTime, int numberMinutes = 1)
{
long roundedMinutesInTicks = LNG_OneMinuteInTicks * numberMinutes;
long remainderTicks = dateTime.Ticks % roundedMinutesInTicks;
if (remainderTicks < roundedMinutesInTicks / 2)
{
// round down
return dateTime.AddTicks(-remainderTicks);
}
// round up
return dateTime.AddTicks(roundedMinutesInTicks - remainderTicks);
}
如果您想使用TimeSpan进行舍入,可以使用它。
/// <summary>
/// Round the datetime
/// </summary>
/// <example>Round(dt, TimeSpan.FromMinutes(5)); => round the time to the nearest 5 minutes.</example>
/// <param name = "dateTime"></param>
/// <param name = "roundBy">The time use to round the time to</param>
/// <returns></returns>
public static DateTime Round(DateTime dateTime, TimeSpan roundBy)
{
long remainderTicks = dateTime.Ticks % roundBy.Ticks;
if (remainderTicks < roundBy.Ticks / 2)
{
// round down
return dateTime.AddTicks(-remainderTicks);
}
// round up
return dateTime.AddTicks(roundBy.Ticks - remainderTicks);
}
答案 11 :(得分:0)
Ramon Smits中带有DateTime.MaxValue检查的解决方案:
DateTime RoundUp(DateTime dt, TimeSpan d) =>
dt switch
{
var max when max.Equals(DateTime.MaxValue) => max,
var v => new DateTime((v.Ticks + d.Ticks - 1) / d.Ticks * d.Ticks, v.Kind)
};
答案 12 :(得分:0)
我的DateTimeOffset版本,基于拉蒙的答案:
public static class DateExtensions
{
public static DateTimeOffset RoundUp(this DateTimeOffset dt, TimeSpan d)
{
return new DateTimeOffset((dt.Ticks + d.Ticks - 1) / d.Ticks * d.Ticks, dt.Offset);
}
}
答案 13 :(得分:0)
您可以尝试以下方法:
string[] parts = ((DateTime)date_time.ToString("HH:mm:ss").Split(':');
int hr = Convert.ToInt32(parts[0]);
int mn = Convert.ToInt32(parts[1]);
int sec2min = (int)Math.Round(Convert.ToDouble(parts[2]) / 60.0, 0);
string adjTime = string.Format("1900-01-01 {0:00}:{1:00}:00.000",
(mn + sec2min > 59 ? (hr + 1 > 23 ? 0 : hr + 1) : hr),
mn + sec2min > 59 ? 60 - mn + sec2min : mn + sec2min);
每个部分(小时,分钟)必须增加并调整为溢出的适当值,例如59分钟> 00,然后将hr加1,如果为23,则小时变为00。 例如将7:34:57舍入为07:35,将9:59:45舍入为10:00,将23:59:45舍入为00:00,这是第二天的时间。
答案 14 :(得分:0)
我见过许多有用的实现,比如来自 @dtb 或 @redent84 的实现。 由于性能差异可以忽略不计,我远离位移并简单地创建可读代码。我经常在我的实用程序库中使用这些扩展。
public static class DateTimeExtensions
{
public static DateTime RoundToTicks(this DateTime target, long ticks) => new DateTime((target.Ticks + ticks / 2) / ticks * ticks, target.Kind);
public static DateTime RoundUpToTicks(this DateTime target, long ticks) => new DateTime((target.Ticks + ticks - 1) / ticks * ticks, target.Kind);
public static DateTime RoundDownToTicks(this DateTime target, long ticks) => new DateTime(target.Ticks / ticks * ticks, target.Kind);
public static DateTime Round(this DateTime target, TimeSpan round) => RoundToTicks(target, round.Ticks);
public static DateTime RoundUp(this DateTime target, TimeSpan round) => RoundUpToTicks(target, round.Ticks);
public static DateTime RoundDown(this DateTime target, TimeSpan round) => RoundDownToTicks(target, round.Ticks);
public static DateTime RoundToMinutes(this DateTime target, int minutes = 1) => RoundToTicks(target, minutes * TimeSpan.TicksPerMinute);
public static DateTime RoundUpToMinutes(this DateTime target, int minutes = 1) => RoundUpToTicks(target, minutes * TimeSpan.TicksPerMinute);
public static DateTime RoundDownToMinutes(this DateTime target, int minutes = 1) => RoundDownToTicks(target, minutes * TimeSpan.TicksPerMinute);
public static DateTime RoundToHours(this DateTime target, int hours = 1) => RoundToTicks(target, hours * TimeSpan.TicksPerHour);
public static DateTime RoundUpToHours(this DateTime target, int hours = 1) => RoundUpToTicks(target, hours * TimeSpan.TicksPerHour);
public static DateTime RoundDownToHours(this DateTime target, int hours = 1) => RoundDownToTicks(target, hours * TimeSpan.TicksPerHour);
public static DateTime RoundToDays(this DateTime target, int days = 1) => RoundToTicks(target, days * TimeSpan.TicksPerDay);
public static DateTime RoundUpToDays(this DateTime target, int days = 1) => RoundUpToTicks(target, days * TimeSpan.TicksPerDay);
public static DateTime RoundDownToDays(this DateTime target, int days = 1) => RoundDownToTicks(target, days * TimeSpan.TicksPerDay);
}