다음을 통해 공유


방법: 날짜 및 시간 값의 밀리초 표시

DateTime.ToString()과 같은 기본 날짜 및 시간 서식 지정 메서드에는 시간 값의 시, 분, 초가 포함되지만 밀리초 구성 요소는 제외됩니다. 이 문서에서는 형식이 지정된 날짜 및 시간 문자열에 날짜 및 시간의 밀리초 구성 요소를 포함하는 방법을 보여 줍니다.

DateTime 값의 밀리초 구성 요소를 표시하려면

  1. 날짜의 문자열 표현에 대한 작업을 하는 경우에는 정적 DateTime 또는 DateTimeOffset 메서드를 사용하여 해당 표현을 DateTime.Parse(String) 또는 DateTimeOffset.Parse(String) 값으로 변환합니다.

  2. 시간 밀리초 구성 요소의 문자열 표현을 추출하려면 날짜 및 시간 값의 DateTime.ToString(String) 또는 ToString 메서드를 호출하고 fff 또는 FFF 사용자 지정 형식 패턴을 단독으로 또는 다른 사용자 지정 형식 지정자와 함께 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: {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"));

    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: {0}",
                    dateValue.ToString(fullPattern));
    Console.WriteLine("Modified full date time pattern: {0}",
                    dateOffsetValue.ToString(fullPattern));
}
catch (FormatException)
{
    Console.WriteLine("Unable to convert {0} to a date.", dateString);
}
// 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 형식 패턴에서는 밀리초 값의 뒤에 0이 포함됩니다. 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 사용자 지정 형식 지정자는 1/10초, ff 또는 FF 사용자 지정 형식 지정자는 1/100초, ffff 또는 FFFF 사용자 지정 형식 지정자는 1/10000초를 표시합니다. 반환된 문자열에서 밀리초의 소수 자릿수가 반올림되지 않고 잘립니다. 이 형식 지정자는 다음 예제에서 사용됩니다.

DateTime dateValue = 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
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

참고 항목

1/10000초, 1/100000초 등 1초의 매우 작은 소수 단위를 표시할 수 있습니다. 그러나 이러한 값은 의미가 없을 수 있습니다. 날짜 및 시간 값의 자릿수는 운영 체제 시계의 정밀도에 따라 달라집니다. 자세한 내용은 운영 체제에서 사용하는 API를 참조하세요.

참고 항목