C# TimeSpan ToString(String)

Description

TimeSpan ToString(String) converts the value of the current TimeSpan object to its equivalent string representation by using the specified format.

Syntax

TimeSpan.ToString(String) has the following syntax.


public string ToString(
  string format
)

Parameters

TimeSpan.ToString(String) has the following parameters.

  • format - A standard or custom TimeSpan format string.

Returns

TimeSpan.ToString(String) method returns The string representation of the current TimeSpan value in the format specified by the format parameter.

Example

The following example uses standard and custom TimeSpan format strings to display the string representation of each element in an array of TimeSpan values


using System;/*  w  ww .ja  v a2  s.  com*/

public class Class1
{
   public static void Main()
   {
      TimeSpan[] spans = { TimeSpan.Zero, new TimeSpan(-14, 0, 0, 0, 0), 
                           new TimeSpan(1, 2, 3), 
                           new TimeSpan(1, 0, 0, 0, 250), 
                           new TimeSpan(99, 23, 59, 59, 999),
                           new TimeSpan(3, 0, 0), 
                           new TimeSpan(1, 0, 1, 0, 25) };
      string[] fmts = { "c", "g", "G", @"hh\:mm\:ss", "%m' min.'" };
      foreach (TimeSpan span in spans)
      {
         foreach (string fmt in fmts)
            Console.WriteLine("{0}: {1}", fmt, span.ToString(fmt));
      }
   }
}

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