默认日期和时间格式设置方法(如 DateTime.ToString())包含时间值的小时、分钟和秒部分,但不包含毫秒部分。 本文说明如何在格式化日期和时间字符串中包含日期和时间的毫秒部分。
显示的 DateTime 值的毫秒部分
- 如果要使用日期的字符串表示形式,请使用静态 DateTime 或 DateTimeOffset 方法将其转换为 DateTime.Parse(String) 或 DateTimeOffset.Parse(String) 值。 
- 若要提取时间值的毫秒部分的字符串表示形式,请调用日期和时间值的 DateTime.ToString(String) 或 ToString 方法,并将 - fff或- FFF自定义格式模式单独传递,或与其他自定义格式说明符一起作为- format参数传递。
示例
此示例展示了如何向控制台传递 DateTime 和 DateTimeOffset 值的毫秒部分(单独传递以及包含在更长的日期和时间字符串中传递)。
using System.Globalization;
using System.Text.RegularExpressions;
string dateString = "7/16/2008 8:32:45.126 AM";
try
{
    DateTime dateValue = DateTime.Parse(dateString);
    DateTimeOffset dateOffsetValue = DateTimeOffset.Parse(dateString);
    // Display Millisecond component alone.
    Console.WriteLine($"Millisecond component only: {dateValue.ToString("fff")}");
    Console.WriteLine($"Millisecond component only: {dateOffsetValue.ToString("fff")}");
    // Display Millisecond component with full date and time.
    Console.WriteLine($"Date and Time with Milliseconds: {dateValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt")}");
    Console.WriteLine($"Date and Time with Milliseconds: {dateOffsetValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt")}");
    string fullPattern = DateTimeFormatInfo.CurrentInfo.FullDateTimePattern;
    
    // Create a format similar to .fff but based on the current culture.
    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}");
    // Display Millisecond component with modified full date and time pattern.
    Console.WriteLine($"Modified full date time pattern: {dateValue.ToString(fullPattern)}");
    Console.WriteLine($"Modified full date time pattern: {dateOffsetValue.ToString(fullPattern)}");
}
catch (FormatException)
{
    Console.WriteLine($"Unable to convert {dateString} to a date.");
}
// The example displays the following output if the current culture is en-US:
//    Millisecond component only: 126
//    Millisecond component only: 126
//    Date and Time with Milliseconds: 07/16/2008 08:32:45.126 AM
//    Date and Time with Milliseconds: 07/16/2008 08:32:45.126 AM
//    Modified full date time pattern: Wednesday, July 16, 2008 8:32:45.126 AM
//    Modified full date time pattern: Wednesday, July 16, 2008 8:32:45.126 AM
Imports System.Globalization
Imports System.Text.REgularExpressions
Module MillisecondDisplay
    Public Sub Main()
        Dim dateString As String = "7/16/2008 8:32:45.126 AM"
        Try
            Dim dateValue As Date = Date.Parse(dateString)
            Dim dateOffsetValue As DateTimeOffset = DateTimeOffset.Parse(dateString)
            ' Display Millisecond component alone.
            Console.WriteLine("Millisecond component only: {0}", _
                              dateValue.ToString("fff"))
            Console.WriteLine("Millisecond component only: {0}", _
                              dateOffsetValue.ToString("fff"))
            ' Display Millisecond component with full date and time.
            Console.WriteLine("Date and Time with Milliseconds: {0}", _
                              dateValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt"))
            Console.WriteLine("Date and Time with Milliseconds: {0}", _
                              dateOffsetValue.ToString("MM/dd/yyyy hh:mm:ss.fff tt"))
            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}")
            ' Display Millisecond component with modified full date and time pattern.
            Console.WriteLine("Modified full date time pattern: {0}", _
                              dateValue.ToString(fullPattern))
            Console.WriteLine("Modified full date time pattern: {0}", _
                              dateOffsetValue.ToString(fullPattern))
        Catch e As FormatException
            Console.WriteLine("Unable to convert {0} to a date.", dateString)
        End Try
    End Sub
End Module
' The example displays the following output if the current culture is en-US:
'    Millisecond component only: 126
'    Millisecond component only: 126
'    Date and Time with Milliseconds: 07/16/2008 08:32:45.126 AM
'    Date and Time with Milliseconds: 07/16/2008 08:32:45.126 AM
'    Modified full date time pattern: Wednesday, July 16, 2008 8:32:45.126 AM
'    Modified full date time pattern: Wednesday, July 16, 2008 8:32:45.126 AM
fff 格式模式包含毫秒值中的任何尾随零。 FFF 格式模式禁止显示它们。 以下示例演示了差异:
DateTime dateValue = new DateTime(2008, 7, 16, 8, 32, 45, 180);
Console.WriteLine(dateValue.ToString("fff"));
Console.WriteLine(dateValue.ToString("FFF"));
// The example displays the following output to the console:
//    180
//    18
Dim dateValue As New Date(2008, 7, 16, 8, 32, 45, 180)
Console.WriteLIne(dateValue.ToString("fff"))
Console.WriteLine(dateValue.ToString("FFF"))
' The example displays the following output to the console:
'    180
'    18
与定义包含日期和时间的毫秒部分的完整自定义格式说明符有关的一个问题在于,它定义可能与应用程序当前区域性中的时间元素排列不对应的硬编码格式。 更好的替换方法是,检索当前区域性的 DateTimeFormatInfo 对象定义的日期和时间显示模式之一,并将它修改为包含毫秒部分。 该示例也阐释了这种方法。 它会从 DateTimeFormatInfo.FullDateTimePattern 属性检索当前区域性的完整日期和时间模式,再插入自定义模式 fff 以及当前区域性的毫秒分隔符。 该示例使用正则表达式在单个方法调用中执行此操作。
还可以使用自定义格式说明符来显示毫秒之外的秒的小数部分。 例如,f 或 F 自定义格式说明符显示十分之几秒,ff 或 FF 自定义格式说明符显示百分之几秒,ffff 或 FFFF 自定义格式说明符显示万分之几秒。 毫秒的小数部分在返回的字符串中会进行截断而不是舍入。 下面的示例中使用了这些格式说明符:
DateTime dateValue = new DateTime(2008, 7, 16, 8, 32, 45, 180);
Console.WriteLine($"{dateValue.ToString("s.f")} seconds");
Console.WriteLine($"{dateValue.ToString("s.ff")} seconds");
Console.WriteLine($"{dateValue.ToString("s.ffff")} seconds");
// The example displays the following output to the console:
//    45.1 seconds
//    45.18 seconds
//    45.1800 seconds
Dim dateValue As New DateTime(2008, 7, 16, 8, 32, 45, 180)
Console.WriteLine("{0} seconds", dateValue.ToString("s.f"))
Console.WriteLine("{0} seconds", dateValue.ToString("s.ff"))
Console.WriteLine("{0} seconds", dateValue.ToString("s.ffff"))
' The example displays the following output to the console:
'    45.1 seconds
'    45.18 seconds
'    45.1800 seconds
注意
可以显示秒的非常小的小数单位,如万分之几秒或十万分之几秒。 但是,这些值可能没有意义。 日期和时间值的精度取决于操作系统时钟的分辨率。 有关详细信息,请参阅操作系统使用的 API:
- Windows 7:GetSystemTimeAsFileTime
- Windows 8 及更高版本:GetSystemTimePreciseAsFileTime
- Linux 和 macOS:clock_gettime