K
K
kxooll2018-07-04 12:14:58
C++ / C#
kxooll, 2018-07-04 12:14:58

Why can't subtract time?

Hello. There is such code -

private DateTime timeStart = DateTime.Now;
        private void WorkTime_Tick(object sender, EventArgs e)
        {
            WorkTimeLabel.Content = "Рабочее время: " + ((DateTime.Now - timeStart).ToString("hh:mm"));
        }

It throws an error -
System.FormatException: 'The input string was not in the correct format.'

Tried different formats, but the same error keeps coming up. How to display time in hours:minutes format?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Nemiro, 2018-07-04
@kxooll

Another DateTime.Subtract can be used:
Separators and other "incomprehensible" characters are best escaped (slash, as shown in the example).
If timeStart is earlier by 24 hours, then this information will not be reflected in the hh:mm format. You can use this option:

WorkTimeLabel.Content = "Рабочее время: " + 
  (DateTime.Now - timeStart).ToString(@"d\д\ hh\:mm").TrimStart('0', 'д').Trim();

See also: stop watch

Дмитрий Еремин, 2018-07-04
@EreminD

TimeSpan

DateTime start = DateTime.Now;
TimeSpan timeDiff = DateTime.Now - start;
timeDiff.Hours;
timeDiff.Minutes;

Посмотрите еще варианты ToString для таймспана

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question