Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: "How to: Display Milliseconds in Date and Time Values"
description: In this article, learn how to include a date and time's millisecond component in formatted date and time strings in .NET.
ms.date: "08/01/2022"
ms.date: 11/30/2026
ms.custom: devdivchpfy22
dev_langs:
- "csharp"
Expand Down Expand Up @@ -39,7 +39,7 @@ The `fff` format pattern includes any trailing zeros in the millisecond value. T
:::code language="csharp" source="snippets/how-to-display-milliseconds-in-date-and-time-values/csharp/Program.cs" id="TrailingZero":::
:::code language="vb" source="snippets/how-to-display-milliseconds-in-date-and-time-values/vb/Program.vb" id="TrailingZero":::

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 might 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?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.
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 might 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?displayProperty=nameWithType> property and then inserts the custom pattern `fff` along with the current culture's millisecond separator. The example scans the pattern from left to right, copies quoted and backslash-escaped literal text unchanged, and appends milliseconds after each seconds specifier (`s` or `ss`). This approach works for cultures that use periods, spaces, or words rather than colons as time separators, and it doesn't treat a literal `s`, such as the `'s'` suffix in some French patterns, as a seconds specifier.

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:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// <Main>
using System.Globalization;
using System.Text.RegularExpressions;
using System.Text;

string dateString = "7/16/2008 8:32:45.126 AM";

Expand All @@ -19,11 +19,11 @@

string fullPattern = DateTimeFormatInfo.CurrentInfo.FullDateTimePattern;

// Create a format similar to .fff but based on the current culture.
string millisecondFormat = $"{NumberFormatInfo.CurrentInfo.NumberDecimalSeparator}fff";
// Create a format similar to .fff but based on the current culture's decimal separator.
string millisecondFormat = $"'{NumberFormatInfo.CurrentInfo.NumberDecimalSeparator}'fff";

// Append millisecond pattern to current culture's full date time pattern.
fullPattern = Regex.Replace(fullPattern, "(:ss|:s)", $"$1{millisecondFormat}");
// Append millisecond pattern to current culture's full date time pattern after its seconds specifier.
fullPattern = AddMilliseconds(fullPattern, millisecondFormat);

// Display Millisecond component with modified full date and time pattern.
Console.WriteLine($"Modified full date time pattern: {dateValue.ToString(fullPattern)}");
Expand All @@ -33,6 +33,61 @@
{
Console.WriteLine($"Unable to convert {dateString} to a date.");
}

// Scans the pattern from left to right, copies quoted and backslash-escaped literal text unchanged,
// and appends the millisecond pattern after each seconds specifier (s or ss).
static string AddMilliseconds(string pattern, string millisecondFormat)
{
var result = new StringBuilder();
int i = 0;
while (i < pattern.Length)
{
char c = pattern[i];
if (c == '\\' && i + 1 < pattern.Length)
{
// Escaped literal character.
result.Append(c).Append(pattern[i + 1]);
i += 2;
}
else if (c == '\'' || c == '"')
{
// Quoted literal string, which can itself contain escaped characters.
result.Append(c);
i++;
while (i < pattern.Length && pattern[i] != c)
{
if (pattern[i] == '\\' && i + 1 < pattern.Length)
{
result.Append(pattern[i]);
i++;
}
result.Append(pattern[i]);
i++;
}
if (i < pattern.Length)
{
result.Append(c);
i++;
}
}
else if (c == 's')
{
// Seconds specifier.
int start = i;
while (i < pattern.Length && pattern[i] == 's')
{
i++;
}
result.Append(pattern, start, i - start).Append(millisecondFormat);
}
else
{
result.Append(c);
i++;
}
}
return result.ToString();
}
// The example displays the following output if the current culture is en-US:
// Millisecond component only: 126
// Millisecond component only: 126
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Option Strict On

' <Main>
Imports System.Globalization
Imports System.Text.REgularExpressions
Imports System.Text

Module MillisecondDisplay
Public Sub Main()
Expand All @@ -28,11 +28,11 @@ Module MillisecondDisplay

Dim fullPattern As String = DateTimeFormatInfo.CurrentInfo.FullDateTimePattern

' Create a format similar to .fff but based on the current culture.
Dim millisecondFormat as String = $"{NumberFormatInfo.CurrentInfo.NumberDecimalSeparator}fff"
' Append millisecond pattern to current culture's full date time pattern.
fullPattern = Regex.Replace(fullPattern, "(:ss|:s)", $"$1{millisecondFormat}")
' Create a format similar to .fff but based on the current culture's decimal separator.
Dim millisecondFormat As String = $"'{NumberFormatInfo.CurrentInfo.NumberDecimalSeparator}'fff"

' Append millisecond pattern to current culture's full date time pattern after its seconds specifier.
fullPattern = AddMilliseconds(fullPattern, millisecondFormat)

' Display Millisecond component with modified full date and time pattern.
Console.WriteLine("Modified full date time pattern: {0}", _
Expand All @@ -43,6 +43,48 @@ Module MillisecondDisplay
Console.WriteLine("Unable to convert {0} to a date.", dateString)
End Try
End Sub

' Scans the pattern from left to right, copies quoted and backslash-escaped literal text unchanged,
' and appends the millisecond pattern after each seconds specifier (s or ss).
Private Function AddMilliseconds(pattern As String, millisecondFormat As String) As String
Dim result As New StringBuilder()
Dim i As Integer = 0
While i < pattern.Length
Dim c As Char = pattern(i)
If c = "\"c AndAlso i + 1 < pattern.Length Then
' Escaped literal character.
result.Append(c).Append(pattern(i + 1))
i += 2
ElseIf c = "'"c OrElse c = """"c Then
' Quoted literal string, which can itself contain escaped characters.
result.Append(c)
i += 1
While i < pattern.Length AndAlso pattern(i) <> c
If pattern(i) = "\"c AndAlso i + 1 < pattern.Length Then
result.Append(pattern(i))
i += 1
End If
result.Append(pattern(i))
i += 1
End While
If i < pattern.Length Then
result.Append(c)
i += 1
End If
ElseIf c = "s"c Then
' Seconds specifier.
Dim start As Integer = i
While i < pattern.Length AndAlso pattern(i) = "s"c
i += 1
End While
result.Append(pattern, start, i - start).Append(millisecondFormat)
Else
result.Append(c)
i += 1
End If
End While
Return result.ToString()
End Function
End Module
' The example displays the following output if the current culture is en-US:
' Millisecond component only: 126
Expand Down