datetime - Get date and time in .NET -


currently trying hour , minute using code:

datetime currentdate = datetime.now.date; int currenthour = datetime.now.date.hour; int currentmin = datetime.now.date.minute; 

but getting 0 instead current hour , minute. how can fix problem?

you're using date property gives midnight @ given datetime. want now:

datetime = datetime.now; int hour = now.hour; int minute = now.minute; datetime date = now.date; // if need 

note code calls datetime.now once, instead of once hours , once minutes1. means if call close (say) 8 a.m., might 7:59 or might 8:00 - won't either 7:00 or 8:59, if had either of these:

// bad option 1 (could 7:00) int hour = datetime.now.hour; // imagine clock rolls on now... int minute = datetime.now.minute;  // bad option 1 (could 8:59) int minute = datetime.now.minute; // imagine clock rolls on now... int hour = datetime.now.hour; 

you should also consider not using datetime.now directly @ all. has 2 problems:

  • it returns time in local time zone; that's okay desktop applications, bad server-side applications
  • it's hard test

if create iclock interface or similar has method or property give current utc time, can convert local time if want (unambiguously, isn't true in reverse) , can inject fake implementation test purposes.

edit: short complete program prove yes, code does work:

using system;  public class test {     static void main(string[] args)     {         datetime = datetime.now;         int hour = now.hour;         int minute = now.minute;         console.writeline(hour);         console.writeline(minute);     } } 

on machine right now, prints 7 , 35. if prints 0 , 0, must midnight on machine.


1 may notice, i've added comment answers continue this. apologies if looks spamming, wanted attention of answerers - it's common error, , 1 i'd eradicate. it's possible without comments, posters have moved on without ever looking again...


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -