DateTime Problem

  • Thread starter Thread starter Jake K
  • Start date Start date
J

Jake K

string var = DateTime.Today.Month.ToString() + "-" +
DateTime.Today.Day.ToString() + "-" + DateTime.Today.Year.ToString() + "-" +
DateTime.Today.Hour.ToString() + "-" + DateTime.Today.Minute.ToString() +
"-" + DateTime.Today.Second.ToString();
MessageBox.Show(var);

returns 12-21-2006-0-0-0

Why would the hours, minute and second not appear correctly?
 
The hours, minute and second appear absolutely correctly because
DateTime.Today returns a DateTime object with just the date, i.e. the time
part all set to 0 (midnight).

Have a look at The DateTime.ToString(format) overloads to make life easier
for yourself.

MessageBox.Show(DateTime.Today.ToString("M-d-y-H-m-s")) and
MessageBox.Show(DateTime.Now.ToString("M-d-y-H-m-s"))

will display:

12-21-2006-0-0-0 and
12-21-2006-12-34-56

respectively if the time is 12:34:56 PM on 21/12/2006.
 
I realise that the problem is resolved, but can I offer some advice?
Either use the format specifiers, or cache the date first, otherwise
you could get anomolies if (for instance) the date ticks over midnight
between calls... and on newyear you could end up printing dates a year
in the future... as in:
[end of 2006]
var = (Dec) + (12)...
[<tick, fireworks, etc> now January]
...+(2007)+(0)+(0)+(0)

i.e.
DateTime when = DateTime.Now;
and work with "when"; the overloads on .ToString() are good too, but
already mentioned by another poster.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top