2

I need to convert a TimeSpan to a string with the format hh:mm tt.

Timespan? tTime;
Console.WriteLine(tTime.ToString("hh:mm tt"));

ToString("hh:mm tt") works well if value is not null, but its causes an error when the value is null.

Is there any solution to this?

user247702
  • 21,902
  • 13
  • 103
  • 146

4 Answers4

3

Just use an if statement or the shortened ? statement. Fill in your desired result in : "" when the value is null

Console.WriteLine(tTime.HasValue ? tTime.Value.ToString("hh:mm tt") : "");
Kevin Cloet
  • 2,836
  • 1
  • 16
  • 34
3

The reason you're getting an error is because tTime.ToString("hh:mm tt") tries to forcibly convert its value to a string, with the required format.
If that value is null, there is no way for the conversion to handle it, thus throwing an error.

One way to do it is by following @KevinCloet's answer, where he simply checks if the tTime has a value, and converts it if it does.

//                validation     ? if true                          : if false
Console.WriteLine(tTime.HasValue ? tTime.Value.ToString("hh:mm tt") : String.Empty);

which could also be written as:

// Boolean values don't need = true
if(tTime.HasValue){
   Console.WriteLine(tTime.Value.ToString("hh:mm tt"));
}else{
   Console.WriteLine(String.Empty);
}

Another way to do it is through a try{}catch(){} method, which is almost the same as the extended if statement

try{
   Console.WriteLine(tTime.Value.ToString("hh:mm tt"));
}
catch(Exception e){
   // You don't actually need the 'Exception e', 
   // however 'e.Message' will tell you exactly what went wrong
   Console.WriteLine(String.Empty);
}

I hope this explanation will help you understand, rather than just give you an answer.

Edit:
Based on Jon Skeets answer on "" vs String.Empty, you can essentially use either.

Community
  • 1
  • 1
TheGeekZn
  • 3,195
  • 7
  • 43
  • 85
  • Exceptions shouldn't be used for your normal flow. [ref 1](http://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control), [ref 2](http://stackoverflow.com/questions/77127/when-to-throw-an-exception). The fact that the variable is nullable indicates that it's *normal* to have a null value. – user247702 May 28 '14 at 11:55
  • @Stijn excellent point out. I was merely showing that theres more than one way to solve an issue. – TheGeekZn May 28 '14 at 12:04
0

You'll need to check for a value first, by using HasValue, or by comparing with null.

However, you also need to use a valid timespan format string. "hh:mm tt" is valid on DateTime, but not on TimeSpan. Try this:

string s = tTime.HasValue ? tTime.Value.ToString("hh\\:mm") : "";
Matt Johnson-Pint
  • 197,368
  • 66
  • 382
  • 508
0

Try the following code:

string time = spantime.HasValue ? spantime.Value.ToString("hh':'mm':'ss") : "??:??:??";
Dmitry
  • 12,938
  • 5
  • 31
  • 46
John
  • 66
  • 1
  • 1
  • 7