Skip to content

Commit f0d64a3

Browse files
authored
Add culture-specific milliseconds format (dotnet#27485)
* copy code * Remove old code * Modify code for milliseconds * Clean article + wording + acro
1 parent d180f03 commit f0d64a3

File tree

6 files changed

+141
-118
lines changed

6 files changed

+141
-118
lines changed

docs/standard/base-types/how-to-display-milliseconds-in-date-and-time-values.md

+31-28
Original file line numberDiff line numberDiff line change
@@ -15,40 +15,43 @@ ms.assetid: ae1a0610-90b9-4877-8eb6-4e30bc5e00cf
1515
---
1616
# How to: Display Milliseconds in Date and Time Values
1717

18-
The default date and time formatting methods, such as <xref:System.DateTime.ToString?displayProperty=nameWithType>, include the hours, minutes, and seconds of a time value but exclude its milliseconds component. This topic shows how to include a date and time's millisecond component in formatted date and time strings.
19-
20-
## To display the millisecond component of a DateTime value
21-
22-
1. If you are working with the string representation of a date, convert it to a <xref:System.DateTime> or a <xref:System.DateTimeOffset> value by using the static <xref:System.DateTime.Parse%28System.String%29?displayProperty=nameWithType> or <xref:System.DateTimeOffset.Parse%28System.String%29?displayProperty=nameWithType> method.
23-
24-
2. To extract the string representation of a time's millisecond component, call the date and time value's <xref:System.DateTime.ToString%28System.String%29?displayProperty=nameWithType> or <xref:System.DateTimeOffset.ToString%2A> method, and pass the `fff` or `FFF` custom format pattern either alone or with other custom format specifiers as the `format` parameter.
25-
26-
## Example
27-
28-
The example displays the millisecond component of a <xref:System.DateTime> and a <xref:System.DateTimeOffset> value to the console, both alone and included in a longer date and time string.
29-
30-
[!code-csharp[Formatting.HowTo.Millisecond#1](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.Millisecond/cs/Millisecond.cs#1)]
31-
[!code-vb[Formatting.HowTo.Millisecond#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Millisecond/vb/Millisecond.vb#1)]
32-
33-
The `fff` format pattern includes any trailing zeros in the millisecond value. The `FFF` format pattern suppresses them. The difference is illustrated in the following example.
34-
35-
[!code-csharp[Formatting.HowTo.Millisecond#2](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.Millisecond/cs/Millisecond.cs#2)]
36-
[!code-vb[Formatting.HowTo.Millisecond#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Millisecond/vb/Millisecond.vb#2)]
37-
38-
A problem with defining a complete custom format specifier that includes the millisecond component of a date and time is that it defines a hard-coded format that may not correspond to the arrangement of time elements in the application's current culture. A better alternative is to retrieve one of the date and time display patterns defined by the current culture's <xref:System.Globalization.DateTimeFormatInfo> object and modify it to include milliseconds. The example also illustrates this approach. It retrieves the current culture's full date and time pattern from the <xref:System.Globalization.DateTimeFormatInfo.FullDateTimePattern%2A?displayProperty=nameWithType> property, and then inserts the custom pattern `.ffff` after its seconds pattern. Note that the example uses a regular expression to perform this operation in a single method call.
39-
40-
You can also use a custom format specifier to display a fractional part of seconds other than milliseconds. For example, the `f` or `F` custom format specifier displays tenths of a second, the `ff` or `FF` custom format specifier displays hundredths of a second, and the `ffff` or `FFFF` custom format specifier displays ten thousandths of a second. Fractional parts of a millisecond are truncated instead of rounded in the returned string. These format specifiers are used in the following example.
41-
42-
[!code-csharp[Formatting.HowTo.Millisecond#3](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.Millisecond/cs/Millisecond.cs#3)]
43-
[!code-vb[Formatting.HowTo.Millisecond#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Millisecond/vb/Millisecond.vb#3)]
44-
18+
The default date and time formatting methods, such as <xref:System.DateTime.ToString?displayProperty=nameWithType>, include the hours, minutes, and seconds of a time value but exclude its milliseconds component. This article shows how to include a date and time's millisecond component in formatted date and time strings.
19+
20+
## To display the millisecond component of a DateTime value
21+
22+
1. If you're working with the string representation of a date, convert it to a <xref:System.DateTime> or a <xref:System.DateTimeOffset> value by using the static <xref:System.DateTime.Parse%28System.String%29?displayProperty=nameWithType> or <xref:System.DateTimeOffset.Parse%28System.String%29?displayProperty=nameWithType> method.
23+
24+
2. To extract the string representation of a time's millisecond component, call the date and time value's <xref:System.DateTime.ToString%28System.String%29?displayProperty=nameWithType> or <xref:System.DateTimeOffset.ToString%2A> method, and pass the `fff` or `FFF` custom format pattern either alone or with other custom format specifiers as the `format` parameter.
25+
26+
> [!TIP]
27+
> The millisecond separator is specified by the <xref:System.Globalization.NumberFormatInfo.NumberDecimalSeparator%2A?displayProperty=fullName> property.
28+
29+
## Example
30+
31+
The example displays the millisecond component of a <xref:System.DateTime> and a <xref:System.DateTimeOffset> value to the console, both alone and included in a longer date and time string.
32+
33+
:::code language="csharp" source="snippets/how-to-display-milliseconds-in-date-and-time-values/csharp/Program.cs" id="Main":::
34+
:::code language="vb" source="snippets/how-to-display-milliseconds-in-date-and-time-values/vb/Program.vb" id="Main":::
35+
36+
The `fff` format pattern includes any trailing zeros in the millisecond value. The `FFF` format pattern suppresses them. The difference is illustrated in the following example.
37+
38+
:::code language="csharp" source="snippets/how-to-display-milliseconds-in-date-and-time-values/csharp/Program.cs" id="TrailingZero":::
39+
:::code language="vb" source="snippets/how-to-display-milliseconds-in-date-and-time-values/vb/Program.vb" id="TrailingZero":::
40+
41+
A problem with defining a complete custom format specifier that includes the millisecond component of a date and time is that it defines a hard-coded format that may not correspond to the arrangement of time elements in the application's current culture. A better alternative is to retrieve one of the date and time display patterns defined by the current culture's <xref:System.Globalization.DateTimeFormatInfo> object and modify it to include milliseconds. The example also illustrates this approach. It retrieves the current culture's full date and time pattern from the <xref:System.Globalization.DateTimeFormatInfo.FullDateTimePattern%2A?displayProperty=nameWithType> property, and then inserts the custom pattern `fff` along with the current culture's millisecond separator. The example uses a regular expression to do this operation in a single method call.
42+
43+
You can also use a custom format specifier to display a fractional part of seconds other than milliseconds. For example, the `f` or `F` custom format specifier displays tenths of a second, the `ff` or `FF` custom format specifier displays hundredths of a second, and the `ffff` or `FFFF` custom format specifier displays ten thousandths of a second. Fractional parts of a millisecond are truncated instead of rounded in the returned string. These format specifiers are used in the following example.
44+
45+
:::code language="csharp" source="snippets/how-to-display-milliseconds-in-date-and-time-values/csharp/Program.cs" id="Fraction":::
46+
:::code language="vb" source="snippets/how-to-display-milliseconds-in-date-and-time-values/vb/Program.vb" id="Fraction":::
47+
4548
> [!NOTE]
4649
> It is possible to display very small fractional units of a second, such as ten thousandths of a second or hundred-thousandths of a second. However, these values may not be meaningful. The precision of a date and time value depends on the resolution of the operating system clock. For more information, see the API your operating system uses:
4750
>
4851
> - Windows 7: [GetSystemTimeAsFileTime](/windows/win32/api/sysinfoapi/nf-sysinfoapi-GetSystemTimeAsFileTime)
4952
> - Windows 8 and above: [GetSystemTimePreciseAsFileTime](/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime)
5053
> - Linux and macOS: [clock_gettime](https://linux.die.net/man/3/clock_gettime)
51-
54+
5255
## See also
5356

5457
- <xref:System.Globalization.DateTimeFormatInfo>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net6.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
</Project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// <Main>
2+
using System.Globalization;
3+
using System.Text.RegularExpressions;
4+
5+
string dateString = "7/16/2008 8:32:45.126 AM";
6+
7+
try
8+
{
9+
DateTime dateValue = DateTime.Parse(dateString);
10+
DateTimeOffset dateOffsetValue = DateTimeOffset.Parse(dateString);
11+
12+
// Display Millisecond component alone.
13+
Console.WriteLine("Millisecond component only: {0}",
14+
dateValue.ToString("fff"));
15+
Console.WriteLine("Millisecond component only: {0}",
16+
dateOffsetValue.ToString("fff"));
17+
18+
// Display Millisecond component with full date and time.
19+
Console.WriteLine("Date and Time with Milliseconds: {0}",
20+
dateValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt"));
21+
Console.WriteLine("Date and Time with Milliseconds: {0}",
22+
dateOffsetValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt"));
23+
24+
string fullPattern = DateTimeFormatInfo.CurrentInfo.FullDateTimePattern;
25+
26+
// Create a format similar to .fff but based on the current culture.
27+
string millisecondFormat = $"{NumberFormatInfo.CurrentInfo.NumberDecimalSeparator}fff";
28+
29+
// Append millisecond pattern to current culture's full date time pattern.
30+
fullPattern = Regex.Replace(fullPattern, "(:ss|:s)", $"$1{millisecondFormat}");
31+
32+
// Display Millisecond component with modified full date and time pattern.
33+
Console.WriteLine("Modified full date time pattern: {0}",
34+
dateValue.ToString(fullPattern));
35+
Console.WriteLine("Modified full date time pattern: {0}",
36+
dateOffsetValue.ToString(fullPattern));
37+
}
38+
catch (FormatException)
39+
{
40+
Console.WriteLine("Unable to convert {0} to a date.", dateString);
41+
}
42+
// The example displays the following output if the current culture is en-US:
43+
// Millisecond component only: 126
44+
// Millisecond component only: 126
45+
// Date and Time with Milliseconds: 07/16/2008 08:32:45.126 AM
46+
// Date and Time with Milliseconds: 07/16/2008 08:32:45.126 AM
47+
// Modified full date time pattern: Wednesday, July 16, 2008 8:32:45.126 AM
48+
// Modified full date time pattern: Wednesday, July 16, 2008 8:32:45.126 AM
49+
// </Main>
50+
51+
public class AdditionalSnippets
52+
{
53+
public static void Show()
54+
{
55+
// <TrailingZero>
56+
DateTime dateValue = new DateTime(2008, 7, 16, 8, 32, 45, 180);
57+
Console.WriteLine(dateValue.ToString("fff"));
58+
Console.WriteLine(dateValue.ToString("FFF"));
59+
// The example displays the following output to the console:
60+
// 180
61+
// 18
62+
// </TrailingZero>
63+
}
64+
65+
public static void Show2()
66+
{
67+
// <Fraction>
68+
DateTime dateValue = new DateTime(2008, 7, 16, 8, 32, 45, 180);
69+
Console.WriteLine("{0} seconds", dateValue.ToString("s.f"));
70+
Console.WriteLine("{0} seconds", dateValue.ToString("s.ff"));
71+
Console.WriteLine("{0} seconds", dateValue.ToString("s.ffff"));
72+
// The example displays the following output to the console:
73+
// 45.1 seconds
74+
// 45.18 seconds
75+
// 45.1800 seconds
76+
// </Fraction>
77+
}
78+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<RootNamespace>DateTimeCode</RootNamespace>
6+
<TargetFramework>net6.0</TargetFramework>
7+
</PropertyGroup>
8+
9+
</Project>

samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.HowTo.Millisecond/vb/Millisecond.vb renamed to docs/standard/base-types/snippets/how-to-display-milliseconds-in-date-and-time-values/vb/Program.vb

+13-9
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
' Visual Basic .NET Document
1+
' Visual Basic .NET Document
22
Option Strict On
33

4-
' <Snippet1>
4+
' <Main>
55
Imports System.Globalization
66
Imports System.Text.REgularExpressions
77

@@ -26,9 +26,13 @@ Module MillisecondDisplay
2626
Console.WriteLine("Date and Time with Milliseconds: {0}", _
2727
dateOffsetValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt"))
2828

29-
' Append millisecond pattern to current culture's full date time pattern
3029
Dim fullPattern As String = DateTimeFormatInfo.CurrentInfo.FullDateTimePattern
31-
fullPattern = Regex.Replace(fullPattern, "(:ss|:s)", "$1.fff")
30+
31+
' Create a format similar to .fff but based on the current culture.
32+
Dim millisecondFormat as String = $"{NumberFormatInfo.CurrentInfo.NumberDecimalSeparator}fff"
33+
34+
' Append millisecond pattern to current culture's full date time pattern.
35+
fullPattern = Regex.Replace(fullPattern, "(:ss|:s)", $"$1{millisecondFormat}")
3236

3337
' Display Millisecond component with modified full date and time pattern.
3438
Console.WriteLine("Modified full date time pattern: {0}", _
@@ -47,23 +51,23 @@ End Module
4751
' Date and Time with Milliseconds: 07/16/2008 08:32:45.126 AM
4852
' Modified full date time pattern: Wednesday, July 16, 2008 8:32:45.126 AM
4953
' Modified full date time pattern: Wednesday, July 16, 2008 8:32:45.126 AM
50-
' </Snippet1>
54+
' </Main>
5155

5256
Public Module AdditionalSnippets
5357

5458
Public Sub Show
55-
' <Snippet2>
59+
' <TrailingZero>
5660
Dim dateValue As New Date(2008, 7, 16, 8, 32, 45, 180)
5761
Console.WriteLIne(dateValue.ToString("fff"))
5862
Console.WriteLine(dateValue.ToString("FFF"))
5963
' The example displays the following output to the console:
6064
' 180
6165
' 18
62-
' </Snippet2>
66+
' </TrailingZero>
6367
End Sub
6468

6569
Public Sub Show2()
66-
' <Snippet3>
70+
' <Fraction>
6771
Dim dateValue As New DateTime(2008, 7, 16, 8, 32, 45, 180)
6872
Console.WriteLine("{0} seconds", dateValue.ToString("s.f"))
6973
Console.WriteLine("{0} seconds", dateValue.ToString("s.ff"))
@@ -72,7 +76,7 @@ Public Module AdditionalSnippets
7276
' 45.1 seconds
7377
' 45.18 seconds
7478
' 45.1800 seconds
75-
' </Snippet3>
79+
' </Fraction>
7680
End Sub
7781

7882
End Module

samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.Millisecond/cs/Millisecond.cs

-81
This file was deleted.

0 commit comments

Comments
 (0)