Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading