Currently I am trying to get the hour and minute using this code:
DateTime currentDate = DateTime.Now.Date;
int currentHour = DateTime.Now.Date.Hour;
int currentMin = DateTime.Now.Date.Minute;
But I am getting zero instead to the current hour and minute. How can I fix this problem?
You’re using the
Dateproperty which gives you midnight at the given DateTime. You just want Now:Note that my code only calls
DateTime.Nowonce, 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:You should also consider not using
DateTime.Nowdirectly at all. It has two problems:If you create an
IClockinterface 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:
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…