1

I am to fill a ddl at run time.

What I actually need to do is pick up the current time from the system (in 24-hour format). Then I need to round it up to a 15 min slot, so if the time is 13:23 it will become 13:30; if it is 13:12 then it should become 13:15.

Then I want to add 45 minutes to it, and 13:15 becomes 14:00.

I am trying to achieve it like this

DateTime d = DateTime.Now;
string hr = d.ToString("HH:mm");
string mi = d.ToString("mm");

Could somebody tell, either I have to write all logic or DateTime can provide some feature to format it like this?

Hans Kesting
  • 36,179
  • 8
  • 79
  • 104
NoviceToDotNet
  • 9,889
  • 32
  • 106
  • 163
  • 1
    This should get you started http://stackoverflow.com/questions/7029353/c-sharp-round-up-time-to-nearest-x-minutes , once you get the rounding part you have `AddMinutes` available – V4Vendetta Apr 04 '13 at 09:03

4 Answers4

2
        DateTime d = DateTime.Now;

        //Add your 45 minutes
        d = d.AddMinutes(45);

        //Add minutes to the next quarter of an hour 
        d = d.AddMinutes((15 - d.TimeOfDay.Minutes % 15) % 15);

        //Show your result
        string hr = d.ToString("HH:mm");
        string mi = d.ToString("mm");
Peter
  • 27,049
  • 8
  • 63
  • 82
2

I think this should do the trick for you:

var d = DateTime.Now;
d = d.AddSeconds(-d.Seconds).AddMilliseconds(-d.Milliseconds)

if (d.Minute < 15) { d.AddMinutes(15 - d.Minute); }
else if (d.Minute < 30) { d = d.AddMinutes(30 - d.Minute); }
else if (d.Minute < 45) { d = d.AddMinutes(45 - d.Minute); }
else if (d.Minute < 60) { d = d.AddMinutes(60 - d.Minute); }

d = d.AddMinutes(45);
Mike Perrenoud
  • 64,877
  • 28
  • 152
  • 226
1

DateTime in C# has a function for adding any increment to the current DateTime object. Here is a reference to the specific function for minutes.

Elad Lachmi
  • 10,338
  • 13
  • 72
  • 131
1
DateTime d = DateTime.Now;

DateTime rounded;
if(d.Minute % 15 ==0)rounded = d;
else DateTime rounded = d.AddMinutes(15 - d.Minute % 15);

Console.WriteLine("{0:HH:mm}",rounded);
Arie
  • 5,009
  • 2
  • 30
  • 51