C# TimeSpan TryParse(String, TimeSpan)

Description

TimeSpan TryParse(String, TimeSpan) converts the string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

Syntax

TimeSpan.TryParse(String, TimeSpan) has the following syntax.


public static bool TryParse(
  string s,
  out TimeSpan result
)

Parameters

TimeSpan.TryParse(String, TimeSpan) has the following parameters.

  • s - A string that specifies the time interval to convert.
  • result - When this method returns, contains an object that represents the time interval specified by s, or TimeSpan.Zero if the conversion failed. This parameter is passed uninitialized.

Returns

TimeSpan.TryParse(String, TimeSpan) method returns true if s was converted successfully; otherwise, false. This operation returns false if the s parameter is null or String.Empty, has an invalid format, represents a time interval that is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.

Example

The following example uses the TryParse method to create TimeSpan objects from valid TimeSpan strings and to indicate when the parse operation has failed because the time span string is invalid.


using System;//from   ww w .j a  v a2s .c om

public class TryParse
{
   public static void Main()
   {

      TimeSpan intervalVal; 
      String intervalStr = "14";
      if (TimeSpan.TryParse(intervalStr, out intervalVal)) 
      {
         string intervalToStr = intervalVal.ToString();

         Console.WriteLine(intervalToStr);

      }

   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version