1
0

Added Collection Extensions, Updated DateTimeExtensions

This commit is contained in:
2024-02-25 09:49:43 +01:00
parent cf425da609
commit 8e31601d75
8 changed files with 242 additions and 27 deletions

View File

@@ -61,20 +61,27 @@ namespace System
public static TimeSpan GetAlignedIntervalLocal(this TimeSpan timeSpan, TimeSpan offset = default)
=> timeSpan.GetAlignedInterval(DateTime.Now, offset);
internal static TimeSpan GetAlignedInterval(this TimeSpan timeSpan, DateTime now, TimeSpan offset = default)
/// <summary>
/// Aligns the <see cref="TimeSpan"/> to the specified time.
/// </summary>
/// <param name="timeSpan">The timespan to align.</param>
/// <param name="now">A timestamp to align with.</param>
/// <param name="offset">A specific offset to the timespan.</param>
/// <returns>The timespan until the aligned time.</returns>
public static TimeSpan GetAlignedInterval(this TimeSpan timeSpan, DateTime now, TimeSpan offset = default)
{
var nowWithOffset = new DateTimeOffset(now);
var dtOffsetNow = new DateTimeOffset(now);
var nextTime = new DateTime(nowWithOffset.Ticks / timeSpan.Ticks * timeSpan.Ticks, now.Kind).Add(offset);
var nextTimeWithOffset = new DateTimeOffset(nextTime);
var nextTime = new DateTime(dtOffsetNow.Ticks / timeSpan.Ticks * timeSpan.Ticks, now.Kind).Add(offset);
var dtOffsetNext = new DateTimeOffset(nextTime);
if (nextTimeWithOffset <= nowWithOffset)
nextTimeWithOffset = nextTimeWithOffset.Add(timeSpan);
if (dtOffsetNext <= dtOffsetNow)
dtOffsetNext = dtOffsetNext.Add(timeSpan);
if (now.Kind == DateTimeKind.Local)
return nextTimeWithOffset.LocalDateTime - nowWithOffset.LocalDateTime;
return dtOffsetNext.LocalDateTime - dtOffsetNow.LocalDateTime;
return nextTimeWithOffset - nowWithOffset;
return dtOffsetNext - dtOffsetNow;
}
#endregion Aligned Interval