简体   繁体   中英

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?

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" .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM