Timespan string format

Timespan string format DEFAULT

usingSystem;

 

publicclassExample

{

    publicstaticvoidMain()

    {

        DateTime now=DateTime.Now;

        DateTime then=newDateTime(2017,12,25);

 

        TimeSpan ts=now-then;

 

        Console.WriteLine(@"{0} Days, {1} Hours, {2} Minutes, {3} Seconds

                            and {4} Milliseconds",ts.Days,ts.Hours,

                            ts.Minutes,ts.Seconds,ts.Milliseconds);

    }

}

 

/*

    Output: 743 Days, 20 Hours, 26 Minutes, 15 Seconds and 84 Milliseconds

*/

Sours: https://www.techiedelight.com/convert-timespan-to-formatted-string-csharp/

Standard TimeSpan format strings

A standard TimeSpan format string uses a single format specifier to define the text representation of a TimeSpan value that results from a formatting operation. Any format string that contains more than one character, including white space, is interpreted as a custom TimeSpan format string. For more information, see Custom TimeSpan format strings .

The string representations of TimeSpan values are produced by calls to the overloads of the TimeSpan.ToString method, as well as by methods that support composite formatting, such as String.Format. For more information, see Formatting Types and Composite Formatting. The following example illustrates the use of standard format strings in formatting operations.

Standard TimeSpan format strings are also used by the TimeSpan.ParseExact and TimeSpan.TryParseExact methods to define the required format of input strings for parsing operations. (Parsing converts the string representation of a value to that value.) The following example illustrates the use of standard format strings in parsing operations.

The following table lists the standard time interval format specifiers.

Format specifierNameDescriptionExamples
"c"Constant (invariant) formatThis specifier is not culture-sensitive. It takes the form .

(The "t" and "T" format strings produce the same results.)

More information: The Constant ("c") Format Specifier.
-> 00:00:00

-> 00:30:00

-> 3.17:25:30.5000000
"g"General short formatThis specifier outputs only what is needed. It is culture-sensitive and takes the form .

More information: The General Short ("g") Format Specifier.
-> 1:3:16:50.5 (en-US)

-> 1:3:16:50,5 (fr-FR)

-> 1:3:16:50.599 (en-US)

-> 1:3:16:50,599 (fr-FR)
"G"General long formatThis specifier always outputs days and seven fractional digits. It is culture-sensitive and takes the form .

More information: The General Long ("G") Format Specifier.
-> 0:18:30:00.0000000 (en-US)

-> 0:18:30:00,0000000 (fr-FR)

The Constant ("c") Format Specifier

The "c" format specifier returns the string representation of a TimeSpan value in the following form:

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

Elements in square brackets ([ and ]) are optional. The period (.) and colon (:) are literal symbols. The following table describes the remaining elements.

ElementDescription
-An optional negative sign, which indicates a negative time interval.
dThe optional number of days, with no leading zeros.
hhThe number of hours, which ranges from "00" to "23".
mmThe number of minutes, which ranges from "00" to "59".
ssThe number of seconds, which ranges from "0" to "59".
fffffffThe optional fractional portion of a second. Its value can range from "0000001" (one tick, or one ten-millionth of a second) to "9999999" (9,999,999 ten-millionths of a second, or one second less one tick).

Unlike the "g" and "G" format specifiers, the "c" format specifier is not culture-sensitive. It produces the string representation of a TimeSpan value that is invariant and that's common to versions prior to .NET Framework 4. "c" is the default TimeSpan format string; the TimeSpan.ToString() method formats a time interval value by using the "c" format string.

Note

TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.

The following example instantiates two TimeSpan objects, uses them to perform arithmetic operations, and displays the result. In each case, it uses composite formatting to display the TimeSpan value by using the "c" format specifier.

The General Short ("g") Format Specifier

The "g" TimeSpan format specifier returns the string representation of a TimeSpan value in a compact form by including only the elements that are necessary. It has the following form:

[-][d:]h:mm:ss[.FFFFFFF]

Elements in square brackets ([ and ]) are optional. The colon (:) is a literal symbol. The following table describes the remaining elements.

ElementDescription
-An optional negative sign, which indicates a negative time interval.
dThe optional number of days, with no leading zeros.
hThe number of hours, which ranges from "0" to "23", with no leading zeros.
mmThe number of minutes, which ranges from "00" to "59"..
ssThe number of seconds, which ranges from "00" to "59"..
.The fractional seconds separator. It is equivalent to the specified culture's NumberDecimalSeparator property without user overrides.
FFFFFFFThe fractional seconds. As few digits as possible are displayed.

Like the "G" format specifier, the "g" format specifier is localized. Its fractional seconds separator is based on either the current culture or a specified culture's NumberDecimalSeparator property.

The following example instantiates two TimeSpan objects, uses them to perform arithmetic operations, and displays the result. In each case, it uses composite formatting to display the TimeSpan value by using the "g" format specifier. In addition, it formats the TimeSpan value by using the formatting conventions of the current system culture (which, in this case, is English - United States or en-US) and the French - France (fr-FR) culture.

The General Long ("G") Format Specifier

The "G" TimeSpan format specifier returns the string representation of a TimeSpan value in a long form that always includes both days and fractional seconds. The string that results from the "G" standard format specifier has the following form:

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

Elements in square brackets ([ and ]) are optional. The colon (:) is a literal symbol. The following table describes the remaining elements.

ElementDescription
-An optional negative sign, which indicates a negative time interval.
dThe number of days, with no leading zeros.
hhThe number of hours, which ranges from "00" to "23".
mmThe number of minutes, which ranges from "00" to "59".
ssThe number of seconds, which ranges from "00" to "59".
.The fractional seconds separator. It is equivalent to the specified culture's NumberDecimalSeparator property without user overrides.
fffffffThe fractional seconds.

Like the "G" format specifier, the "g" format specifier is localized. Its fractional seconds separator is based on either the current culture or a specified culture's NumberDecimalSeparator property.

The following example instantiates two TimeSpan objects, uses them to perform arithmetic operations, and displays the result. In each case, it uses composite formatting to display the TimeSpan value by using the "G" format specifier. In addition, it formats the TimeSpan value by using the formatting conventions of the current system culture (which, in this case, is English - United States or en-US) and the French - France (fr-FR) culture.

See also

Sours: https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-timespan-format-strings
  1. Airedale rescue oklahoma
  2. Reddit yiff
  3. Mpt recharge

Custom TimeSpan format strings

A TimeSpan format string defines the string representation of a TimeSpan value that results from a formatting operation. A custom format string consists of one or more custom TimeSpan format specifiers along with any number of literal characters. Any string that isn't a Standard TimeSpan format string is interpreted as a custom TimeSpan format string.

Important

The custom TimeSpan format specifiers don't include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.

Custom TimeSpan format specifiers also don't include a sign symbol that enables you to differentiate between negative and positive time intervals. To include a sign symbol, you have to construct a format string by using conditional logic. The Other characters section includes an example.

The string representations of TimeSpan values are produced by calls to the overloads of the TimeSpan.ToString method, and by methods that support composite formatting, such as String.Format. For more information, see Formatting Types and Composite Formatting. The following example illustrates the use of custom format strings in formatting operations.

Custom TimeSpan format strings are also used by the TimeSpan.ParseExact and TimeSpan.TryParseExact methods to define the required format of input strings for parsing operations. (Parsing converts the string representation of a value to that value.) The following example illustrates the use of standard format strings in parsing operations.

The following table describes the custom date and time format specifiers.

Format specifierDescriptionExample
"d", "%d"The number of whole days in the time interval.

More information: The "d" custom format specifier.


--> "6"

--> "6.14:32"
"dd"-"dddddddd"The number of whole days in the time interval, padded with leading zeros as needed.

More information: The "dd"-"dddddddd" custom format specifiers.


--> "006"

--> "06.14:32"
"h", "%h"The number of whole hours in the time interval that aren't counted as part of days. Single-digit hours don't have a leading zero.

More information: The "h" custom format specifier.


--> "14"

--> "14:32"
"hh"The number of whole hours in the time interval that aren't counted as part of days. Single-digit hours have a leading zero.

More information: The "hh" custom format specifier.


--> "14"



--> 08
"m", "%m"The number of whole minutes in the time interval that aren't included as part of hours or days. Single-digit minutes don't have a leading zero.

More information: The "m" custom format specifier.


--> "8"

--> "14:8"
"mm"The number of whole minutes in the time interval that aren't included as part of hours or days. Single-digit minutes have a leading zero.

More information: The "mm" custom format specifier.


--> "08"



--> 6.08:05:17
"s", "%s"The number of whole seconds in the time interval that aren't included as part of hours, days, or minutes. Single-digit seconds don't have a leading zero.

More information: The "s" custom format specifier.
:

--> 12

--> 12.965
"ss"The number of whole seconds in the time interval that aren't included as part of hours, days, or minutes. Single-digit seconds have a leading zero.

More information: The "ss" custom format specifier.
:

--> 06

--> 06.965
"f", "%f"The tenths of a second in a time interval.

More information: The "f" custom format specifier.
:

--> 8

--> 06.8
"ff"The hundredths of a second in a time interval.

More information: The "ff" custom format specifier.
:

--> 89

--> 06.89
"fff"The milliseconds in a time interval.

More information: The "fff" custom format specifier.
:

--> 895

--> 06.895
"ffff"The ten-thousandths of a second in a time interval.

More information: The "ffff" custom format specifier.
:

--> 8954

--> 06.8954
"fffff"The hundred-thousandths of a second in a time interval.

More information: The "fffff" custom format specifier.
:

--> 89543

--> 06.89543
"ffffff"The millionths of a second in a time interval.

More information: The "ffffff" custom format specifier.
:

--> 895432

--> 06.895432
"fffffff"The ten-millionths of a second (or the fractional ticks) in a time interval.

More information: The "fffffff" custom format specifier.
:

--> 8954321

--> 06.8954321
"F", "%F"The tenths of a second in a time interval. Nothing is displayed if the digit is zero.

More information: The "F" custom format specifier.
:

: 3

:

: 03.
"FF"The hundredths of a second in a time interval. Any fractional trailing zeros or two zero digits aren't included.

More information: The "FF" custom format specifier.
:

: 32

:

: 03.1
"FFF"The milliseconds in a time interval. Any fractional trailing zeros aren't included.

More information:
:

: 329

:

: 03.1
"FFFF"The ten-thousandths of a second in a time interval. Any fractional trailing zeros aren't included.

More information: The "FFFF" custom format specifier.
:

: 3291

:

: 03.1
"FFFFF"The hundred-thousandths of a second in a time interval. Any fractional trailing zeros aren't included.

More information: The "FFFFF" custom format specifier.
:

: 32917

:

: 03.1
"FFFFFF"The millionths of a second in a time interval. Any fractional trailing zeros aren't displayed.

More information: The "FFFFFF" custom format specifier.
:

: 329179

:

: 03.1
"FFFFFFF"The ten-millions of a second in a time interval. Any fractional trailing zeros or seven zeros aren't displayed.

More information: The "FFFFFFF" custom format specifier.
:

: 3291791

:

: 03.19
'string'Literal string delimiter.

More information: Other characters.


--> "14:32:17"
\The escape character.

More information: Other characters.


--> "14:32:17"
Any other characterAny other unescaped character is interpreted as a custom format specifier.

More Information: Other characters.


--> "14:32:17"

The "d" custom format specifier

The "d" custom format specifier outputs the value of the TimeSpan.Days property, which represents the number of whole days in the time interval. It outputs the full number of days in a TimeSpan value, even if the value has more than one digit. If the value of the TimeSpan.Days property is zero, the specifier outputs "0".

If the "d" custom format specifier is used alone, specify "%d" so that it isn't misinterpreted as a standard format string. The following example provides an illustration.

The following example illustrates the use of the "d" custom format specifier.

Back to table

The "dd"-"dddddddd" custom format specifiers

The "dd", "ddd", "dddd", "ddddd", "dddddd", "ddddddd", and "dddddddd" custom format specifiers output the value of the TimeSpan.Days property, which represents the number of whole days in the time interval.

The output string includes a minimum number of digits specified by the number of "d" characters in the format specifier, and it's padded with leading zeros as needed. If the digits in the number of days exceed the number of "d" characters in the format specifier, the full number of days is output in the result string.

The following example uses these format specifiers to display the string representation of two TimeSpan values. The value of the days component of the first time interval is zero; the value of the days component of the second is 365.

Back to table

The "h" custom format specifier

The "h" custom format specifier outputs the value of the TimeSpan.Hours property, which represents the number of whole hours in the time interval that isn't counted as part of its day component. It returns a one-digit string value if the value of the TimeSpan.Hours property is 0 through 9, and it returns a two-digit string value if the value of the TimeSpan.Hours property ranges from 10 to 23.

If the "h" custom format specifier is used alone, specify "%h" so that it isn't misinterpreted as a standard format string. The following example provides an illustration.

Ordinarily, in a parsing operation, an input string that includes only a single number is interpreted as the number of days. You can use the "%h" custom format specifier instead to interpret the numeric string as the number of hours. The following example provides an illustration.

The following example illustrates the use of the "h" custom format specifier.

Back to table

The "hh" custom format specifier

The "hh" custom format specifier outputs the value of the TimeSpan.Hours property, which represents the number of whole hours in the time interval that isn't counted as part of its day component. For values from 0 through 9, the output string includes a leading zero.

Ordinarily, in a parsing operation, an input string that includes only a single number is interpreted as the number of days. You can use the "hh" custom format specifier instead to interpret the numeric string as the number of hours. The following example provides an illustration.

The following example illustrates the use of the "hh" custom format specifier.

Back to table

The "m" custom format specifier

The "m" custom format specifier outputs the value of the TimeSpan.Minutes property, which represents the number of whole minutes in the time interval that isn't counted as part of its day component. It returns a one-digit string value if the value of the TimeSpan.Minutes property is 0 through 9, and it returns a two-digit string value if the value of the TimeSpan.Minutes property ranges from 10 to 59.

If the "m" custom format specifier is used alone, specify "%m" so that it isn't misinterpreted as a standard format string. The following example provides an illustration.

Ordinarily, in a parsing operation, an input string that includes only a single number is interpreted as the number of days. You can use the "%m" custom format specifier instead to interpret the numeric string as the number of minutes. The following example provides an illustration.

The following example illustrates the use of the "m" custom format specifier.

Back to table

The "mm" custom format specifier

The "mm" custom format specifier outputs the value of the TimeSpan.Minutes property, which represents the number of whole minutes in the time interval that isn't included as part of its hours or days component. For values from 0 through 9, the output string includes a leading zero.

Ordinarily, in a parsing operation, an input string that includes only a single number is interpreted as the number of days. You can use the "mm" custom format specifier instead to interpret the numeric string as the number of minutes. The following example provides an illustration.

The following example illustrates the use of the "mm" custom format specifier.

Back to table

The "s" custom format specifier

The "s" custom format specifier outputs the value of the TimeSpan.Seconds property, which represents the number of whole seconds in the time interval that isn't included as part of its hours, days, or minutes component. It returns a one-digit string value if the value of the TimeSpan.Seconds property is 0 through 9, and it returns a two-digit string value if the value of the TimeSpan.Seconds property ranges from 10 to 59.

If the "s" custom format specifier is used alone, specify "%s" so that it isn't misinterpreted as a standard format string. The following example provides an illustration.

Ordinarily, in a parsing operation, an input string that includes only a single number is interpreted as the number of days. You can use the "%s" custom format specifier instead to interpret the numeric string as the number of seconds. The following example provides an illustration.

The following example illustrates the use of the "s" custom format specifier.

Back to table

The "ss" custom format specifier

The "ss" custom format specifier outputs the value of the TimeSpan.Seconds property, which represents the number of whole seconds in the time interval that isn't included as part of its hours, days, or minutes component. For values from 0 through 9, the output string includes a leading zero.

Ordinarily, in a parsing operation, an input string that includes only a single number is interpreted as the number of days. You can use the "ss" custom format specifier instead to interpret the numeric string as the number of seconds. The following example provides an illustration.

The following example illustrates the use of the "ss" custom format specifier.

Back to table

The "f" custom format specifier

The "f" custom format specifier outputs the tenths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the input string must contain exactly one fractional digit.

If the "f" custom format specifier is used alone, specify "%f" so that it isn't misinterpreted as a standard format string.

The following example uses the "f" custom format specifier to display the tenths of a second in a TimeSpan value. "f" is used first as the only format specifier, and then combined with the "s" specifier in a custom format string.

Back to table

The "ff" custom format specifier

The "ff" custom format specifier outputs the hundredths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the input string must contain exactly two fractional digits.

The following example uses the "ff" custom format specifier to display the hundredths of a second in a TimeSpan value. "ff" is used first as the only format specifier, and then combined with the "s" specifier in a custom format string.

Back to table

The "fff" custom format specifier

The "fff" custom format specifier (with three "f" characters) outputs the milliseconds in a time interval. In a formatting operation, any remaining fractional digits are truncated. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the input string must contain exactly three fractional digits.

The following example uses the "fff" custom format specifier to display the milliseconds in a TimeSpan value. "fff" is used first as the only format specifier, and then combined with the "s" specifier in a custom format string.

Back to table

The "ffff" custom format specifier

The "ffff" custom format specifier (with four "f" characters) outputs the ten-thousandths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the input string must contain exactly four fractional digits.

The following example uses the "ffff" custom format specifier to display the ten-thousandths of a second in a TimeSpan value. "ffff" is used first as the only format specifier, and then combined with the "s" specifier in a custom format string.

Back to table

The "fffff" custom format specifier

The "fffff" custom format specifier (with five "f" characters) outputs the hundred-thousandths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the input string must contain exactly five fractional digits.

The following example uses the "fffff" custom format specifier to display the hundred-thousandths of a second in a TimeSpan value. "fffff" is used first as the only format specifier, and then combined with the "s" specifier in a custom format string.

Back to table

The "ffffff" custom format specifier

The "ffffff" custom format specifier (with six "f" characters) outputs the millionths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the input string must contain exactly six fractional digits.

The following example uses the "ffffff" custom format specifier to display the millionths of a second in a TimeSpan value. It is used first as the only format specifier, and then combined with the "s" specifier in a custom format string.

Back to table

The "fffffff" custom format specifier

The "fffffff" custom format specifier (with seven "f" characters) outputs the ten-millionths of a second (or the fractional number of ticks) in a time interval. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the input string must contain exactly seven fractional digits.

The following example uses the "fffffff" custom format specifier to display the fractional number of ticks in a TimeSpan value. It is used first as the only format specifier, and then combined with the "s" specifier in a custom format string.

Back to table

The "F" custom format specifier

The "F" custom format specifier outputs the tenths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. If the value of the time interval's tenths of a second is zero, it isn't included in the result string. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the presence of the tenths of a second digit is optional.

If the "F" custom format specifier is used alone, specify "%F" so that it isn't misinterpreted as a standard format string.

The following example uses the "F" custom format specifier to display the tenths of a second in a TimeSpan value. It also uses this custom format specifier in a parsing operation.

Back to table

The "FF" custom format specifier

The "FF" custom format specifier outputs the hundredths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. If there are any trailing fractional zeros, they aren't included in the result string. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the presence of the tenths and hundredths of a second digit is optional.

The following example uses the "FF" custom format specifier to display the hundredths of a second in a TimeSpan value. It also uses this custom format specifier in a parsing operation.

Back to table

The "FFF" custom format specifier

The "FFF" custom format specifier (with three "F" characters) outputs the milliseconds in a time interval. In a formatting operation, any remaining fractional digits are truncated. If there are any trailing fractional zeros, they aren't included in the result string. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the presence of the tenths, hundredths, and thousandths of a second digit is optional.

The following example uses the "FFF" custom format specifier to display the thousandths of a second in a TimeSpan value. It also uses this custom format specifier in a parsing operation.

Back to table

The "FFFF" custom format specifier

The "FFFF" custom format specifier (with four "F" characters) outputs the ten-thousandths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. If there are any trailing fractional zeros, they aren't included in the result string. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the presence of the tenths, hundredths, thousandths, and ten-thousandths of a second digit is optional.

The following example uses the "FFFF" custom format specifier to display the ten-thousandths of a second in a TimeSpan value. It also uses the "FFFF" custom format specifier in a parsing operation.

Back to table

The "FFFFF" custom format specifier

The "FFFFF" custom format specifier (with five "F" characters) outputs the hundred-thousandths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. If there are any trailing fractional zeros, they aren't included in the result string. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the presence of the tenths, hundredths, thousandths, ten-thousandths, and hundred-thousandths of a second digit is optional.

The following example uses the "FFFFF" custom format specifier to display the hundred-thousandths of a second in a TimeSpan value. It also uses the "FFFFF" custom format specifier in a parsing operation.

Back to table

The "FFFFFF" custom format specifier

The "FFFFFF" custom format specifier (with six "F" characters) outputs the millionths of a second in a time interval. In a formatting operation, any remaining fractional digits are truncated. If there are any trailing fractional zeros, they aren't included in the result string. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the presence of the tenths, hundredths, thousandths, ten-thousandths, hundred-thousandths, and millionths of a second digit is optional.

The following example uses the "FFFFFF" custom format specifier to display the millionths of a second in a TimeSpan value. It also uses this custom format specifier in a parsing operation.

Back to table

The "FFFFFFF" custom format specifier

The "FFFFFFF" custom format specifier (with seven "F" characters) outputs the ten-millionths of a second (or the fractional number of ticks) in a time interval. If there are any trailing fractional zeros, they aren't included in the result string. In a parsing operation that calls the TimeSpan.ParseExact or TimeSpan.TryParseExact method, the presence of the seven fractional digits in the input string is optional.

The following example uses the "FFFFFFF" custom format specifier to display the fractional parts of a second in a TimeSpan value. It also uses this custom format specifier in a parsing operation.

Back to table

Other characters

Any other unescaped character in a format string, including a white-space character, is interpreted as a custom format specifier. In most cases, the presence of any other unescaped character results in a FormatException.

There are two ways to include a literal character in a format string:

  • Enclose it in single quotation marks (the literal string delimiter).

  • Precede it with a backslash ("\"), which is interpreted as an escape character. This means that, in C#, the format string must either be @-quoted, or the literal character must be preceded by an additional backslash.

    In some cases, you may have to use conditional logic to include an escaped literal in a format string. The following example uses conditional logic to include a sign symbol for negative time intervals.

.NET doesn't define a grammar for separators in time intervals. This means that the separators between days and hours, hours and minutes, minutes and seconds, and seconds and fractions of a second must all be treated as character literals in a format string.

The following example uses both the escape character and the single quote to define a custom format string that includes the word "minutes" in the output string.

Back to table

See also

Sours: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings
C# Keywords (System.DateTime \u0026 System.Timespan)

Standard TimeSpan format strings

titledescriptionms.datems.topicdev_langshelpviewer_keywordsms.assetid

Standard TimeSpan format strings

Review standard TimeSpan format strings, which use a single format specifier to define the text representation of a TimeSpan value in .NET.

03/30/2017

reference

format specifiers, standard time interval

format strings

standard time interval format strings

standard format strings, time intervals

format specifiers, time intervals

time intervals [.NET], formatting

time [.NET], formatting

formatting [.NET], time

standard TimeSpan format strings

formatting [.NET], time intervals

9f6c95eb-63ae-4dcc-9c32-f81985c75794

A standard xref:System.TimeSpan format string uses a single format specifier to define the text representation of a xref:System.TimeSpan value that results from a formatting operation. Any format string that contains more than one character, including white space, is interpreted as a custom xref:System.TimeSpan format string. For more information, see Custom TimeSpan format strings .

The string representations of xref:System.TimeSpan values are produced by calls to the overloads of the xref:System.TimeSpan.ToString%2A?displayProperty=nameWithType method, as well as by methods that support composite formatting, such as xref:System.String.Format%2A?displayProperty=nameWithType. For more information, see Formatting Types and Composite Formatting. The following example illustrates the use of standard format strings in formatting operations.

[!code-csharpConceptual.TimeSpan.Standard#2] [!code-vbConceptual.TimeSpan.Standard#2]

Standard xref:System.TimeSpan format strings are also used by the xref:System.TimeSpan.ParseExact%2A?displayProperty=nameWithType and xref:System.TimeSpan.TryParseExact%2A?displayProperty=nameWithType methods to define the required format of input strings for parsing operations. (Parsing converts the string representation of a value to that value.) The following example illustrates the use of standard format strings in parsing operations.

[!code-csharpConceptual.TimeSpan.Standard#3] [!code-vbConceptual.TimeSpan.Standard#3]

The following table lists the standard time interval format specifiers.

Format specifierNameDescriptionExamples
"c"Constant (invariant) formatThis specifier is not culture-sensitive. It takes the form .

(The "t" and "T" format strings produce the same results.)

More information: The Constant ("c") Format Specifier.
-> 00:00:00

-> 00:30:00

-> 3.17:25:30.5000000
"g"General short formatThis specifier outputs only what is needed. It is culture-sensitive and takes the form .

More information: The General Short ("g") Format Specifier.
-> 1:3:16:50.5 (en-US)

-> 1:3:16:50,5 (fr-FR)

-> 1:3:16:50.599 (en-US)

-> 1:3:16:50,599 (fr-FR)
"G"General long formatThis specifier always outputs days and seven fractional digits. It is culture-sensitive and takes the form .

More information: The General Long ("G") Format Specifier.
-> 0:18:30:00.0000000 (en-US)

-> 0:18:30:00,0000000 (fr-FR)

The Constant ("c") Format Specifier

The "c" format specifier returns the string representation of a xref:System.TimeSpan value in the following form:

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

Elements in square brackets ([ and ]) are optional. The period (.) and colon (:) are literal symbols. The following table describes the remaining elements.

ElementDescription
-An optional negative sign, which indicates a negative time interval.
dThe optional number of days, with no leading zeros.
hhThe number of hours, which ranges from "00" to "23".
mmThe number of minutes, which ranges from "00" to "59".
ssThe number of seconds, which ranges from "0" to "59".
fffffffThe optional fractional portion of a second. Its value can range from "0000001" (one tick, or one ten-millionth of a second) to "9999999" (9,999,999 ten-millionths of a second, or one second less one tick).

Unlike the "g" and "G" format specifiers, the "c" format specifier is not culture-sensitive. It produces the string representation of a xref:System.TimeSpan value that is invariant and that's common to versions prior to .NET Framework 4. "c" is the default xref:System.TimeSpan format string; the xref:System.TimeSpan.ToString?displayProperty=nameWithType method formats a time interval value by using the "c" format string.

[!NOTE] xref:System.TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.

The following example instantiates two xref:System.TimeSpan objects, uses them to perform arithmetic operations, and displays the result. In each case, it uses composite formatting to display the xref:System.TimeSpan value by using the "c" format specifier.

[!code-csharpConceptual.TimeSpan.Standard#1] [!code-vbConceptual.TimeSpan.Standard#1]

The General Short ("g") Format Specifier

The "g" xref:System.TimeSpan format specifier returns the string representation of a xref:System.TimeSpan value in a compact form by including only the elements that are necessary. It has the following form:

[-][d:]h:mm:ss[.FFFFFFF]

Elements in square brackets ([ and ]) are optional. The colon (:) is a literal symbol. The following table describes the remaining elements.

ElementDescription
-An optional negative sign, which indicates a negative time interval.
dThe optional number of days, with no leading zeros.
hThe number of hours, which ranges from "0" to "23", with no leading zeros.
mmThe number of minutes, which ranges from "00" to "59"..
ssThe number of seconds, which ranges from "00" to "59"..
.The fractional seconds separator. It is equivalent to the specified culture's xref:System.Globalization.NumberFormatInfo.NumberDecimalSeparator%2A property without user overrides.
FFFFFFFThe fractional seconds. As few digits as possible are displayed.

Like the "G" format specifier, the "g" format specifier is localized. Its fractional seconds separator is based on either the current culture or a specified culture's xref:System.Globalization.NumberFormatInfo.NumberDecimalSeparator%2A property.

The following example instantiates two xref:System.TimeSpan objects, uses them to perform arithmetic operations, and displays the result. In each case, it uses composite formatting to display the xref:System.TimeSpan value by using the "g" format specifier. In addition, it formats the xref:System.TimeSpan value by using the formatting conventions of the current system culture (which, in this case, is English - United States or en-US) and the French - France (fr-FR) culture.

[!code-csharpConceptual.TimeSpan.Standard#4] [!code-vbConceptual.TimeSpan.Standard#4]

The General Long ("G") Format Specifier

The "G" xref:System.TimeSpan format specifier returns the string representation of a xref:System.TimeSpan value in a long form that always includes both days and fractional seconds. The string that results from the "G" standard format specifier has the following form:

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

Elements in square brackets ([ and ]) are optional. The colon (:) is a literal symbol. The following table describes the remaining elements.

ElementDescription
-An optional negative sign, which indicates a negative time interval.
dThe number of days, with no leading zeros.
hhThe number of hours, which ranges from "00" to "23".
mmThe number of minutes, which ranges from "00" to "59".
ssThe number of seconds, which ranges from "00" to "59".
.The fractional seconds separator. It is equivalent to the specified culture's xref:System.Globalization.NumberFormatInfo.NumberDecimalSeparator%2A property without user overrides.
fffffffThe fractional seconds.

Like the "G" format specifier, the "g" format specifier is localized. Its fractional seconds separator is based on either the current culture or a specified culture's xref:System.Globalization.NumberFormatInfo.NumberDecimalSeparator%2A property.

The following example instantiates two xref:System.TimeSpan objects, uses them to perform arithmetic operations, and displays the result. In each case, it uses composite formatting to display the xref:System.TimeSpan value by using the "G" format specifier. In addition, it formats the xref:System.TimeSpan value by using the formatting conventions of the current system culture (which, in this case, is English - United States or en-US) and the French - France (fr-FR) culture.

[!code-csharpConceptual.TimeSpan.Standard#5] [!code-vbConceptual.TimeSpan.Standard#5]

See also

Sours: https://github.com/dotnet/docs/blob/main/docs/standard/base-types/standard-timespan-format-strings.md

Format timespan string

When working on our .NET apps, it’s not uncommon that to have date calculations or other logic that requires us to use objects. If we’re internationalizing our apps, we may want to format these s in a culture-aware way.

Built-in Options

Suppose we have two s and we subtract them to get a interval.

using System; class MainClass { public static void Main (string[] args) { var dateTime1 = new DateTime(1970, 1, 1, 0, 0, 0); var dateTime2 = new DateTime(2020, 4, 1, 13, 30, 22, 500); TimeSpan span = dateTime2 - dateTime1; Console.WriteLine(span.ToString()); // => 18353.13:30:22.5000000 Console.WriteLine(span.ToString(@"hh\:mm\:ss")); // => 13:30:22 } }

The built-in gives us some formatting options. We can pass it no arguments to get the constant (invariant) format, which looks like (days.hours:minues:seconds.ten-millionths-of-a-second).

We can also pass a custom string as we do in the above call, . This uses custom format specifiers to gives us a string formatted in an exact way, which, unfortunately, is not culture-aware.

🔗 Resource » See all custom TimeSpan format strings on Microsoft’s .NET docs.

There is an overload of that takes an , which gives us some culture-sensitivity.

using System; using System.Globalization; class MainClass { public static void Main (string[] args) { var dateTime1 = new DateTime(1970, 1, 1, 0, 0, 0); var dateTime2 = new DateTime(2020, 4, 1, 13, 30, 22, 500); TimeSpan span = dateTime2 - dateTime1; Console.WriteLine(span.ToString("G", new CultureInfo("en-US"))); // => 18353:13:30:22.5000000 Console.WriteLine(span.ToString("G", new CultureInfo("fr-FR"))); // => 18353:13:30:22,5000000 Console.WriteLine(span.ToString("G", new CultureInfo("ml-IN"))); // => 18353:13:30:22.5000000 } }

Notice that when we pass a French object (which conforms to ), the decimal separator used is a comma (,), not a dot (.). This is the correct decimal separator for French.

However, the time-separator used is always a colon (:), regardless of culture. This is evident in the Malayalam, India locale above. The official Malayalam time separator is a dot (.), and yet the formatted string uses a colon (:). This limitation may well be the correct behavior for localized time interval representation, although I couldn’t find a reliable standard for localized time intervals when I researched this.

🔗 Resource » The localizable version of only accepts standard format strings ( or or ). Check out the standard TimeSpan format strings on Microsoft’s .NET docs.

The Workaround

Regardless of the “correct” behavior of localized time interval formatting, we may have a case in our app where we want to format a such that it mimics a culture’s hour-minute-second representation. We can write a custom extension method to achieve this.

using System; using System.Globalization; public static class TimeSpanExtensions { public static string LocalizedTimeFormat( this TimeSpan timeSpan, CultureInfo cultureInfo) { string formattedTimeSpan = timeSpan.ToString(@"hh\:mm\:ss"); string timeSeparator = cultureInfo.DateTimeFormat.TimeSeparator; return formattedTimeSpan.Replace(":", timeSeparator); } } class MainClass { public static void Main (string[] args) { var dateTime1 = new DateTime(1970, 1, 1, 0, 0, 0); var dateTime2 = new DateTime(2020, 4, 1, 13, 30, 22, 500); TimeSpan span = dateTime2 - dateTime1; Console.WriteLine(span.LocalizedTimeFormat(new CultureInfo("en-US"))); // => 13:30:22 Console.WriteLine(span.LocalizedTimeFormat(new CultureInfo("fr-FR"))); // => 13:30:22 Console.WriteLine(span.LocalizedTimeFormat(new CultureInfo("ml-IN"))); // => 13.30.22 } }

Our extension method, , simply formats the using a custom format. It then uses the culture-aware from its given , and does a string ment, switching out colons for the culture’s time separator.

In the third call above, the Malaylam output is , which reflects that culture’s usual hour-minute-second representation —using a dot (.) separator instead of a colon (:).

Til Next Time

The real-world needs of our apps will sometimes mean extending .NET’s built-in i18n functionality to solve our problems. Creative extensions are part of the fun of programming; however, the tedium of juggling string files between translators in a localized app is not.

That’s where Phrase comes in. Built by developers for developers, and featuring a sleek web console for translators, two-way string sync via CLI, over-the-air (OTA) translations for mobile apps, and a ton of integrations and extensibility, Phrase does the heavy i18n lifting so you can focus on the code you love. Check out all of Phrase’s features, and sign up for a free 14-day trial.


Authored by Mohammad. Last updated on .

Sours: https://phrase.com/blog/posts/format-hhmmss-timespan-separators-culture-aware-manner/
109. The String.format() method - Learn Java

Convert TimeSpan from format "hh:mm:ss" to "hh:mm"

You need to convert your data to TimeSpan and then use format:

In your case:

Remember to escape the colon

You may see: Custom TimeSpan Format Strings


There is no need to convert from to . is stored as a number of ticks (1 tick == 100 nanoseconds) and has no inherent format. What you have to do, is to convert the into a human readable string! This involves formatting. If you do not specify a format explicitly, a default format will be used. In this case .

Note: This overload of exists since .NET 4.0. It does not support date and time placeholder separator symbols! Therefore you must include them as (escaped) string literals.

The usual way of formatting strings seems not to work for some odd reason (tested with .NET 3.5). (It does not make any difference whether you escape the separator symbol or not):

However, you can construct the string like this

or starting with VS2015 / C# 6.0, using string interpolation:


You can use TimeSpan methods:

Also check all available formats here http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Sours: https://newbedev.com/convert-timespan-from-format-hh-mm-ss-to-hh-mm

Similar news:

.



1657 1658 1659 1660 1661