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
  • 38,117
  • 9
  • 79
  • 111
NoviceToDotNet
  • 10,387
  • 36
  • 112
  • 166
  • 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,590
  • 8
  • 64
  • 84
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
  • 66,820
  • 29
  • 157
  • 232
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,406
  • 13
  • 71
  • 133
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,251
  • 2
  • 33
  • 54