共用方式為


如何顯示日期和時間中的毫秒

默認日期和時間格式方法,例如 DateTime.ToString(),包含時間值的小時、分鐘和秒,但排除其毫秒元件。 本文說明如何在格式化日期和時間字串中包含日期和時間的毫秒元件。

顯示 DateTime 值的毫秒元件

  1. 如果您正在處理日期的字串表示形式,請使用靜態 DateTime.Parse(String) 方法或 DateTimeOffset.Parse(String) 方法將其轉換為 DateTimeDateTimeOffset 值。

  2. 若要擷取時間毫秒元件的字串表示,請呼叫日期和時間值的 DateTime.ToString(String)ToString 方法,並單獨傳遞 fffFFF 自定義格式模式,或使用其他自定義格式規範做為 format 參數。

小提示

屬性 System.Globalization.NumberFormatInfo.NumberDecimalSeparator 會指定毫秒分隔符。

範例

此範例會將的毫秒元件 DateTimeDateTimeOffset 值單獨顯示在控制台中,並包含在較長的日期和時間字串中。

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 以及目前文化特性的毫秒分隔符。 此範例會使用正則表達式在單一方法呼叫中執行這項作業。

您也可以使用自訂格式規範來顯示毫秒以外的秒數部分。 例如,fF自定義格式規範會顯示秒的十分之一,ffFF自定義格式規範會顯示十分之一秒,或ffffFFFF自定義格式規範會顯示每秒的十萬分之一。 毫秒的小數部分會被截斷,而不是在傳回的字串中四捨五入。 下列範例會使用這些格式規範:

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:

另請參閱