You're using the Date property which gives you midnight at the given DateTime. You just want Now:
DateTime now = DateTime.Now; int hour = now.Hour; int minute = now.Minute; DateTime date = now.Date; // If you really need it
Note that my code only calls DateTime.Now once, instead of once for hours and then once for minutes1. That means if you call it close to (say) 8 A.M., you might get 7:59 or you might get 8:00 - but you won't get either 7:00 or 8:59, which you could get if you had either of these:
// Bad option 1 (could get 7:00) int hour = DateTime.Now.Hour; // Imagine the clock rolls over now... int minute = DateTime.Now.Minute; // Bad option 1 (could get 8:59) int minute = DateTime.Now.Minute; // Imagine the clock rolls over now... int hour = DateTime.Now.Hour;
You should also consider not using DateTime.Now directly at all. It has two problems:
- It returns the time in the local time zone; that's probably okay for desktop applications, but bad for server-side applications
- It's hard to test
If you create an IClock interface or something similar which has a method or property to give you the current UTC time, you can always convert that to local time if you want (unambiguously, which isn't true in reverse) and you can also inject a fake implementation for test purposes.
EDIT: A short but complete program to prove that yes, this code really does work:
using System; public class Test { static void Main(string[] args) { DateTime now = DateTime.Now; int hour = now.Hour; int minute = now.Minute; Console.WriteLine(hour); Console.WriteLine(minute); } }
On my machine right now, that prints 7 and then 35. If it prints 0 and then 0, then it must be midnight on your machine.
1 As you may notice, I've added a comment to all the answers which continue to do this. Apologies if this looks like spamming, but I wanted to get the attention of those answerers - it's a common error, and one which I'd like to help eradicate. It's possible that without the comments, posters would have just moved on without ever looking again...