1

I have a program that manages clients arrival, and whenever a new client is created, the TimeSpan property TimeOfArrival is assigned the current time of day with :

TimeSpan TimeOfArrival = DateTime.Now.TimeOfDay;

Now I'm trying to put that in a more convenient format that way :

string ShortTime = TimeOfArrival.ToString("hh:mm");

Though now I get the following exception :

System.FormatException: 'Input string was not in a correct format.'

I can't seem to understand what the problem is. I checked and TimeOfArrival actually has a correct TimeSpan value right before I get the exception. That exception wouldn't surprise me if I was trying to parse an user input into a TimeSpan, but there I'm confused. Could anyone help ? Thanks in advance

Marcel Barc
  • 137
  • 1
  • 9

2 Answers2

3

You're super close.

Simply change to the string format being passed in to:

string ShortTime = TimeOfArrival.ToString(@"hh\:mm");

See TimeSpan.ToString() for more examples.

That exception wouldn't surprise me if I was trying to parse an user input into a TimeSpan, but there I'm confused.

So the thing being parsed and is not in the correct format is the string being passed to ToString(); there is nothing wrong with TimeOfArrival at all.

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • Thank you, indeed that was close. Funny I've been looking for the answer for hours though I haven't come upon any of the duplicates pointed above nor the msdn reference for TimeSpan.ToString(), guess I'm tired ;) – Marcel Barc May 14 '19 at 21:16
  • It happens, my friend. Glad you've got an answer and can sleep tonight. ;) – Idle_Mind May 14 '19 at 21:21
2

As seen in MSDN's Example , the format should be of the form:

@"hh\:mm".

"h'h 'm'm" should work as well.

Avi Meltser
  • 409
  • 4
  • 11