laurent
laurent

Reputation: 3

DateTime.ToString FormatException error

I want to do a timer and print the value in a label. I do:

label1.Text = (DateTime.Now - startDate).ToString("HH:mm:ss");

But I receive a FormatException error. What's wrong in my code?

Upvotes: 0

Views: 677

Answers (2)

Arun
Arun

Reputation: 851

label1.Text = DateTime.Compare(Convert.ToDateTime(startDate.Text), Convert.ToDateTime(ToDate.Text,"hh\\:mm\\:ss"));

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460138

DateTime.Now - startDate returns a TimeSpan not a DateTime.

You need to escape colons with backslash and use lowercase hh in TimeSpan.ToString:

TimeSpan diff = DateTime.Now - startDate;
label1.Text = diff.ToString("hh\\:mm\\:ss");

But note that the hour will never exceed 23 hours, the maximum value is 23:59:59. If you want to show also the days you have to use a format like "dd\\:hh\\:mm\\:ss".

Upvotes: 3

Related Questions