1

Is there a simple method to round up DateTime to the nearest minute? i.e.. 2011-08-11 16:58:20 becomes 2011-08-11 16:59:00

I have already tried several solutions

dt.AddMinutes((60 - dt.Minute) % 10);

but that seems to add 1 whole minute.

McNets
  • 10,352
  • 3
  • 32
  • 61
Monty
  • 1,534
  • 2
  • 10
  • 12

1 Answers1

1

As @ChristofWollenhaupt mentioned in comments section

Rounding should base on the Ticks property not Second. Otherwise rounded DateTime still have different values for milliseconds

If that's the case then create new DateTime and make correction to minutes based on ticks.

TimeSpan timeSpan = new TimeSpan(0, 0, 0, dt.Second, dt.Millisecond);
DateTime roundedDateTime = new DateTime(
    dt.Year,
    dt.Month,
    dt.Day,
    dt.Hour,
    dt.Minute,
    0,        //Second
    0,        //Millisecond
    dt.Kind
    );
roundedDateTime.AddMinutes(timeSpan.Ticks > 0 ? 1 : 0);
DotNet Developer
  • 2,973
  • 1
  • 15
  • 24
  • 2
    You say "do not add" and then do an add? – DavidG May 31 '22 at 08:37
  • @DotNetDeveloper Why not add or subtract? – Johnathan Barclay May 31 '22 at 08:39
  • 1
    OP doesn't add/subtract from the current DateTime though. – DavidG May 31 '22 at 08:42
  • ^^ _"**Returns a new DateTime** that adds the specified number of minutes to the value of this instance."_ - [DateTime.AddMinutes(Double) Method](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.addminutes?view=net-6.0) – Fildor May 31 '22 at 08:47
  • As the dupe's answers and @ChristofWollenhaupt in comments above say: it's better (i.e. more correct) to round based on Ticks. – Fildor May 31 '22 at 08:57
  • @DotNetDeveloper This looks better, but we still have the issue with Ticks with your answer based on the unclear question of the OP. What if, the original DateTime was 2011-08-11 16:58:20.999. Your code rounds this down to 2011-08-11 16:58:20. – Christof Wollenhaupt May 31 '22 at 09:12