Home > OS >  How do I get the latest full hour minus one hour in C#?
How do I get the latest full hour minus one hour in C#?

Time:09-17

Let's say that DateTime.Now is 13:26. How do I get 12:00 from this? I need to find the latest full hour and then go back further one hour. Or go back one hour and then find the latest full hour, whichever way... How do I achieve this in C#?

I tried now.AddHours(-1); to remove the first hour, but I don't know how to go back to 00 minutes. Is there a good and clean way of doing this?

CodePudding user response:

DateTime.Today.AddHours(DateTime.Now.Hour - 1);

This takes the current Date (with Time set to zero) and only adds the desired amount of hours back on.

No need to deal with minutes, seconds, ticks etc.

CodePudding user response:

You could construct a new DateTime in order to truncate it, then take off an hour

var dt = DateTime.Now;
dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0, dt.Kind).AddHours(-1);

This correctly deals with the hour being 0

CodePudding user response:

Try Something like this,

DateTime.Now.AddMinutes(-DateTime.Now.Minute).AddHours(-1)
  • Related