- Dealing with hours with no minutes when rounding DateTime to the 30 minutes
- protected DateTime GetStartTime()
- {
- var spanTicks = TimeSpan.FromMinutes(30).Ticks;
- var ticks = (Time.Now.Ticks + spanTicks - 1) / spanTicks;
- return new DateTime(ticks * spanTicks);
- }
- var now = DateTime.Now;
- DateTime result = now.AddMinutes(now.Minute >= 30 ? (60-now.Minute) : (30-now.Minute));
- result = result.AddSeconds(-1* result.Second); // To reset seconds to 0
- result = result.AddMilliseconds(-1* result.Millisecond); // To reset milliseconds to 0
- protected DateTime GetStartTime() {
- var now = DateTime.Now;
- int addHours;
- int minute;
- if (now.Minute >= 30) {
- addHour = 1;
- minute = 0;
- } else {
- addHour = 0;
- minute = 30;
- }
- return new DateTime(now.Year, now.Month, now.Day, hour, minute, 0).AddHours(addHours);
- }
- protected DateTime GetStartTime()
- {
- DateTime dt=DateTime.Now;
- if (dt.Minute<30)
- {
- dt=dt.AddMinutes(30-dt.Minute);
- }
- else
- {
- dt=dt.AddMinutes(60-dt.Minute);
- }
- //dt now has the upcoming half-hour border
- //...
- }
- 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;
- }
- }
- 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;
- }
- }
- }