แก้ไข

แชร์ผ่าน


TimeSpan.ToString Method

Definition

Converts the value of the current TimeSpan object to its equivalent string representation.

Overloads

ToString()

Converts the value of the current TimeSpan object to its equivalent string representation.

ToString(String)

Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format.

ToString(String, IFormatProvider)

Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format and culture-specific formatting information.

ToString()

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Converts the value of the current TimeSpan object to its equivalent string representation.

public:
 override System::String ^ ToString();
public override string ToString ();
override this.ToString : unit -> string
Public Overrides Function ToString () As String

Returns

The string representation of the current TimeSpan value.

Examples

The following example displays the strings returned by calling the ToString method with a number of TimeSpan values. Note that although the example does not call the ToString method directly, it is called by the Console.WriteLine method when it attempts to convert a TimeSpan value to its string representation.

 TimeSpan span;
 
 // Initialize a time span to zero.
 span = TimeSpan.Zero;
 Console.WriteLine(span);

 // Initialize a time span to 14 days.
 span = new TimeSpan(-14, 0, 0, 0, 0);
 Console.WriteLine(span);

 // Initialize a time span to 1:02:03.
 span = new TimeSpan(1, 2, 3);
 Console.WriteLine(span);

 // Initialize a time span to 250 milliseconds.
 span = new TimeSpan(0, 0, 0, 0, 250);
 Console.WriteLine(span);
 
 // Initialize a time span to 99 days, 23 hours, 59 minutes, and 59.999 seconds.
 span = new TimeSpan(99, 23, 59, 59, 999);
 Console.WriteLine(span);
 
 // Initialize a time span to 3 hours.
 span = new TimeSpan(3, 0, 0);
 Console.WriteLine(span);
 
 // Initialize a timespan to 25 milliseconds.
 span = new TimeSpan(0, 0, 0, 0, 25);
 Console.WriteLine(span);

 // The example displays the following output:
 //       00:00:00
 //       -14.00:00:00
 //       01:02:03
 //       00:00:00.2500000
 //       99.23:59:59.9990000
 //       03:00:00
 //       00:00:00.0250000
// Initialize a time span to zero.
let span = TimeSpan.Zero
printfn $"{span}"

// Initialize a time span to 14 days.
let span = TimeSpan(-14, 0, 0, 0, 0)
printfn $"{span}"

// Initialize a time span to 1:02:03.
let span = TimeSpan(1, 2, 3)
printfn $"{span}"

// Initialize a time span to 250 milliseconds.
let span = TimeSpan(0, 0, 0, 0, 250)
printfn $"{span}"

// Initialize a time span to 99 days, 23 hours, 59 minutes, and 59.999 seconds.
let span = TimeSpan(99, 23, 59, 59, 999)
printfn $"{span}"

// Initialize a time span to 3 hours.
let span = TimeSpan(3, 0, 0)
printfn $"{span}"

// Initialize a timespan to 25 milliseconds.
let span = TimeSpan(0, 0, 0, 0, 25)
printfn $"{span}"

// The example displays the following output:
//       00:00:00
//       -14.00:00:00
//       01:02:03
//       00:00:00.2500000
//       99.23:59:59.9990000
//       03:00:00
//       00:00:00.0250000
Module ToString
   Public Sub Main()
      Dim span As TimeSpan
      
      ' Initialize a time span to zero.
      span = TimeSpan.Zero
      Console.WriteLine(span)
      
      ' Initialize a time span to 14 days.
      span = New TimeSpan(-14, 0, 0, 0, 0)
      Console.WriteLine(span)
     
      ' Initialize a time span to 1:02:03.
      span = New TimeSpan(1, 2, 3)
      Console.WriteLine(span)
      
      
      ' Initialize a time span to 250 milliseconds.
      span = New TimeSpan(0, 0, 0, 0, 250)
      Console.WriteLine(span)
      
      ' Initialize a time span to 99 days, 23 hours, 59 minutes, and 59.9999999 seconds.
      span = New TimeSpan(99, 23, 59, 59, 999)
      Console.WriteLine(span)
      
      ' Initialize a time span to 3 hours.
      span = New TimeSpan(3, 0, 0)
      Console.WriteLine(span)
      
      ' Initialize a timespan to 25 milliseconds.
      span = New TimeSpan(0, 0, 0, 0, 25)
      Console.WriteLine(span)
   End Sub
End Module
' The example displays the following output:
'       00:00:00
'       -14.00:00:00
'       01:02:03
'       00:00:00.2500000
'       99.23:59:59.9990000
'       03:00:00
'       00:00:00.0250000

Remarks

The returned string is formatted with the "c" format specifier and has the following format:

[-][d.]hh:mm:ss[.fffffff]

Elements in square brackets ([ and ]) may not be included in the returned string. Colons and periods (: and.) are literal characters. The non-literal elements are listed in the following table. Note that the string returned by the ToString() method is not culture-sensitive.

Item Description
"-" A minus sign, which indicates a negative time interval. No sign is included for a positive time span.
"d" The number of days in the time interval. This element is omitted if the time interval is less than one day.
"hh" The number of hours in the time interval, ranging from 0 to 23.
"mm" The number of minutes in the time interval, ranging from 0 to 59.
"ss" The number of seconds in the time interval, ranging from 0 to 59.
"fffffff" Fractional seconds in the time interval. This element is omitted if the time interval does not include fractional seconds. If present, fractional seconds are always expressed using seven decimal digits.

Notes to Callers

Support for formatting TimeSpan values was added in the .NET Framework 4. However, the ToString() method overload remains culture-insensitive. Its behavior remains unchanged from previous versions of the .NET Framework. To control the formatting of a TimeSpan value, call the ToString(String) or ToString(String, IFormatProvider) overload.

See also

Applies to

ToString(String)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format.

public:
 System::String ^ ToString(System::String ^ format);
public string ToString (string format);
public string ToString (string? format);
override this.ToString : string -> string
Public Function ToString (format As String) As String

Parameters

format
String

A standard or custom TimeSpan format string.

Returns

The string representation of the current TimeSpan value in the format specified by the format parameter.

Exceptions

The format parameter is not recognized or is not supported.

Examples

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

TimeSpan[] spans = { 
   TimeSpan.Zero, 
   new TimeSpan(-14, 0, 0, 0, 0), 
   new TimeSpan(1, 2, 3), 
   new TimeSpan(0, 0, 0, 0, 250), 
   new TimeSpan(99, 23, 59, 59, 999),
   new TimeSpan(3, 0, 0), 
   new TimeSpan(0, 0, 0, 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));

   Console.WriteLine();
}
// The example displays the following output:
//       c: 00:00:00
//       g: 0:00:00
//       G: 0:00:00:00.0000000
//       hh\:mm\:ss: 00:00:00
//       %m' min.': 0 min.
//       
//       c: -14.00:00:00
//       g: -14:0:00:00
//       G: -14:00:00:00.0000000
//       hh\:mm\:ss: 00:00:00
//       %m' min.': 0 min.
//       
//       c: 01:02:03
//       g: 1:02:03
//       G: 0:01:02:03.0000000
//       hh\:mm\:ss: 01:02:03
//       %m' min.': 2 min.
//       
//       c: 00:00:00.2500000
//       g: 0:00:00.25
//       G: 0:00:00:00.2500000
//       hh\:mm\:ss: 00:00:00
//       %m' min.': 0 min.
//       
//       c: 99.23:59:59.9990000
//       g: 99:23:59:59.999
//       G: 99:23:59:59.9990000
//       hh\:mm\:ss: 23:59:59
//       %m' min.': 59 min.
//       
//       c: 03:00:00
//       g: 3:00:00
//       G: 0:03:00:00.0000000
//       hh\:mm\:ss: 03:00:00
//       %m' min.': 0 min.
//       
//       c: 00:00:00.0250000
//       g: 0:00:00.025
//       G: 0:00:00:00.0250000
//       hh\:mm\:ss: 00:00:00
//       %m' min.': 0 min.
let spans = 
    [| TimeSpan.Zero
       TimeSpan(-14, 0, 0, 0, 0)
       TimeSpan(1, 2, 3)
       TimeSpan(0, 0, 0, 0, 250)
       TimeSpan(99, 23, 59, 59, 999)
       TimeSpan(3, 0, 0)
       TimeSpan(0, 0, 0, 0, 25) |]


let fmts = [| "c"; "g"; "G"; @"hh\:mm\:ss"; "%m' min.'" |]
for span in spans do
    for fmt in fmts do
        printfn $"{fmt}: {span.ToString fmt}"
    printfn ""
// The example displays the following output:
//       c: 00:00:00
//       g: 0:00:00
//       G: 0:00:00:00.0000000
//       hh\:mm\:ss: 00:00:00
//       %m' min.': 0 min.
//       
//       c: -14.00:00:00
//       g: -14:0:00:00
//       G: -14:00:00:00.0000000
//       hh\:mm\:ss: 00:00:00
//       %m' min.': 0 min.
//       
//       c: 01:02:03
//       g: 1:02:03
//       G: 0:01:02:03.0000000
//       hh\:mm\:ss: 01:02:03
//       %m' min.': 2 min.
//       
//       c: 00:00:00.2500000
//       g: 0:00:00.25
//       G: 0:00:00:00.2500000
//       hh\:mm\:ss: 00:00:00
//       %m' min.': 0 min.
//       
//       c: 99.23:59:59.9990000
//       g: 99:23:59:59.999
//       G: 99:23:59:59.9990000
//       hh\:mm\:ss: 23:59:59
//       %m' min.': 59 min.
//       
//       c: 03:00:00
//       g: 3:00:00
//       G: 0:03:00:00.0000000
//       hh\:mm\:ss: 03:00:00
//       %m' min.': 0 min.
//       
//       c: 00:00:00.0250000
//       g: 0:00:00.025
//       G: 0:00:00:00.0250000
//       hh\:mm\:ss: 00:00:00
//       %m' min.': 0 min.
Module Example
   Public Sub Main()
      Dim spans() As TimeSpan = { TimeSpan.Zero, New TimeSpan(-14, 0, 0, 0, 0), 
                                  New TimeSpan(1, 2, 3), 
                                  New TimeSpan(0, 0, 0, 0, 250), 
                                  New TimeSpan(99, 23, 59, 59, 999),
                                  New TimeSpan(3, 0, 0), 
                                  New TimeSpan(0, 0, 0, 0, 25) }
      Dim fmts() As String = { "c", "g", "G", "hh\:mm\:ss", "%m' min.'" }
      For Each span As TimeSpan In spans
         For Each fmt As String In fmts
            Console.WriteLine("{0}: {1}", fmt, span.ToString(fmt))
         Next
         Console.WriteLine()         
      Next
   End Sub
End Module
' The example displays the following output:
'       c: 00:00:00
'       g: 0:00:00
'       G: 0:00:00:00.0000000
'       hh\:mm\:ss: 00:00:00
'       %m' min.': 0 min.
'       
'       c: -14.00:00:00
'       g: -14:0:00:00
'       G: -14:00:00:00.0000000
'       hh\:mm\:ss: 00:00:00
'       %m' min.': 0 min.
'       
'       c: 01:02:03
'       g: 1:02:03
'       G: 0:01:02:03.0000000
'       hh\:mm\:ss: 01:02:03
'       %m' min.': 2 min.
'       
'       c: 00:00:00.2500000
'       g: 0:00:00.25
'       G: 0:00:00:00.2500000
'       hh\:mm\:ss: 00:00:00
'       %m' min.': 0 min.
'       
'       c: 99.23:59:59.9990000
'       g: 99:23:59:59.999
'       G: 99:23:59:59.9990000
'       hh\:mm\:ss: 23:59:59
'       %m' min.': 59 min.
'       
'       c: 03:00:00
'       g: 3:00:00
'       G: 0:03:00:00.0000000
'       hh\:mm\:ss: 03:00:00
'       %m' min.': 0 min.
'       
'       c: 00:00:00.0250000
'       g: 0:00:00.025
'       G: 0:00:00:00.0250000
'       hh\:mm\:ss: 00:00:00
'       %m' min.': 0 min.

Remarks

The format parameter can be any valid standard or custom format specifier for TimeSpan values. If format is equal to String.Empty or is null, the return value of the current TimeSpan object is formatted with the common format specifier ("c"). If format is any other value, the method throws a FormatException.

If format is a standard format string, the format of the returned string is defined by the formatting conventions of the current culture.

Important

The custom format strings for TimeSpan values do not include a date or time separator. If you want to include these elements in your format string, you must treat them as character literals. See the example for an illustration, and see the Custom TimeSpan Format Strings topic for more information.

.NET provides extensive formatting support, which is described in greater detail in the following formatting topics:

See also

Applies to

ToString(String, IFormatProvider)

Source:
TimeSpan.cs
Source:
TimeSpan.cs
Source:
TimeSpan.cs

Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format and culture-specific formatting information.

public:
 virtual System::String ^ ToString(System::String ^ format, IFormatProvider ^ formatProvider);
public string ToString (string format, IFormatProvider formatProvider);
public string ToString (string? format, IFormatProvider? formatProvider);
override this.ToString : string * IFormatProvider -> string
Public Function ToString (format As String, formatProvider As IFormatProvider) As String

Parameters

format
String

A standard or custom TimeSpan format string.

formatProvider
IFormatProvider

An object that supplies culture-specific formatting information.

Returns

The string representation of the current TimeSpan value, as specified by format and formatProvider.

Implements

Exceptions

The format parameter is not recognized or is not supported.

Examples

The following example calls the ToString(String, IFormatProvider) method to format two time intervals. The example calls the method twice for each format string, first to display it using the conventions of the en-US culture and then to display it using the conventions of the fr-FR culture.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      TimeSpan[] intervals = { new TimeSpan(38, 30, 15), 
                               new TimeSpan(16, 14, 30) }; 
      CultureInfo[] cultures = { new CultureInfo("en-US"), 
                                 new CultureInfo("fr-FR") };
      string[] formats = {"c", "g", "G", @"hh\:mm\:ss" };
      Console.WriteLine("{0,12}      Format  {1,22}  {2,22}\n", 
                        "Interval", cultures[0].Name, cultures[1].Name);

      foreach (var interval in intervals) {
         foreach (var fmt in formats)
            Console.WriteLine("{0,12}  {1,10}  {2,22}  {3,22}", 
                              interval, fmt, 
                              interval.ToString(fmt, cultures[0]), 
                              interval.ToString(fmt, cultures[1]));
         Console.WriteLine();
      }  
   }
}
// The example displays the following output:
//        Interval      Format                   en-US                   fr-FR
//    
//      1.14:30:15           c              1.14:30:15              1.14:30:15
//      1.14:30:15           g              1:14:30:15              1:14:30:15
//      1.14:30:15           G      1:14:30:15.0000000      1:14:30:15,0000000
//      1.14:30:15  hh\:mm\:ss                14:30:15                14:30:15
//    
//        16:14:30           c                16:14:30                16:14:30
//        16:14:30           g                16:14:30                16:14:30
//        16:14:30           G      0:16:14:30.0000000      0:16:14:30,0000000
//        16:14:30  hh\:mm\:ss                16:14:30                16:14:30
open System
open System.Globalization

let intervals = 
    [| TimeSpan(38, 30, 15)
       TimeSpan(16, 14, 30) |] 
let cultures = 
    [| CultureInfo "en-US"
       CultureInfo "fr-FR" |]
let formats = [| "c"; "g"; "G"; @"hh\:mm\:ss" |]
printfn $"""{"Interval",12}      Format  {cultures[0].Name,22}  {cultures[1].Name,22}\n""" 

for interval in intervals do
    for fmt in formats do
        printfn $"{interval,12}  {fmt,10}  {interval.ToString(fmt, cultures[0]),22}  {interval.ToString(fmt, cultures[1]),22}"
    printfn ""
// The example displays the following output:
//        Interval      Format                   en-US                   fr-FR
//    
//      1.14:30:15           c              1.14:30:15              1.14:30:15
//      1.14:30:15           g              1:14:30:15              1:14:30:15
//      1.14:30:15           G      1:14:30:15.0000000      1:14:30:15,0000000
//      1.14:30:15  hh\:mm\:ss                14:30:15                14:30:15
//    
//        16:14:30           c                16:14:30                16:14:30
//        16:14:30           g                16:14:30                16:14:30
//        16:14:30           G      0:16:14:30.0000000      0:16:14:30,0000000
//        16:14:30  hh\:mm\:ss                16:14:30                16:14:30
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim intervals() As TimeSpan = { New TimeSpan(38, 30, 15), 
                                      New TimeSpan(16, 14, 30) } 
      Dim cultures() As CultureInfo = { New CultureInfo("en-US"), 
                                        New CultureInfo("fr-FR") }
      Dim formats() As String = {"c", "g", "G", "hh\:mm\:ss" }
      Console.WriteLine("{0,12}      Format  {1,22}  {2,22}", 
                        "Interval", cultures(0).Name, cultures(1).Name)
      Console.WriteLine()
      For Each interval In intervals
         For Each fmt In formats
            Console.WriteLine("{0,12}  {1,10}  {2,22}  {3,22}", 
                              interval, fmt, 
                              interval.ToString(fmt, cultures(0)), 
                              interval.ToString(fmt, cultures(1)))
         Next
         Console.WriteLine()
      Next                                                                                                                                            
   End Sub
End Module
' The example displays the following output:
'        Interval      Format                   en-US                   fr-FR
'    
'      1.14:30:15           c              1.14:30:15              1.14:30:15
'      1.14:30:15           g              1:14:30:15              1:14:30:15
'      1.14:30:15           G      1:14:30:15.0000000      1:14:30:15,0000000
'      1.14:30:15  hh\:mm\:ss                14:30:15                14:30:15
'    
'        16:14:30           c                16:14:30                16:14:30
'        16:14:30           g                16:14:30                16:14:30
'        16:14:30           G      0:16:14:30.0000000      0:16:14:30,0000000
'        16:14:30  hh\:mm\:ss                16:14:30                16:14:30

Remarks

The format parameter can be any valid standard or custom format specifier for TimeSpan values. If format is equal to String.Empty or is null, the return value of the current TimeSpan object is formatted with the common format specifier ("c"). If format is any other value, the method throws a FormatException.

Important

The custom format strings for TimeSpan values do not include a date or time separator. If you want to include these elements in your format string, you must treat them as character literals. See the example for an illustration, and see the Custom TimeSpan Format Strings topic for more information.

.NET provides extensive formatting support, which is described in greater detail in the following formatting topics:

The formatProvider parameter is an IFormatProvider implementation that provides culture-specific information about the format of the returned string. The formatProvider parameter can be any of the following:

If formatProvider is null, the DateTimeFormatInfo object that is associated with the current culture is used. If format is a custom format string, the formatProvider parameter is ignored.

See also

Applies to