다음을 통해 공유


방법: 특정 날짜에서 요일 추출

.NET을 사용하면 특정 날짜의 요일을 쉽게 확인하고 특정 날짜의 지역화된 요일 이름을 표시할 수 있습니다. 특정 날짜에 해당하는 요일을 나타내는 열거형 값은 DayOfWeek 속성 또는 DayOfWeek 속성에서 확인할 수 있습니다. 반면, 요일 이름 검색은 날짜 및 시간 값의 ToString 메서드 또는 String.Format와 같은 메서드를 호출하여 수행할 수 있는 서식 지정 작업입니다. 이 문서에서는 이러한 서식 지정 작업을 수행하는 방법을 보여 줍니다.

요일을 나타내는 숫자 추출

  1. 정적(정적) DateTime.Parse 또는 DateTimeOffset.Parse 메서드를 사용하여 날짜의 문자열 표현을 DateTime 또는 DateTimeOffset 값으로 변환합니다.

  2. DateTime.DayOfWeek 또는 DateTimeOffset.DayOfWeek 속성을 사용하여 값을 검색하면 요일을 나타내는 DayOfWeek을 얻을 수 있습니다.

  3. 필요한 경우 C#으로 캐스팅하거나(Visual Basic에서) DayOfWeek 값을 정수로 변환합니다.

다음 예제에서는 특정 날짜의 요일을 나타내는 정수입니다.

using System;

public class Example
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2008, 6, 11);
      Console.WriteLine((int) dateValue.DayOfWeek);
   }
}
// The example displays the following output:
//       3
Module Example
    Public Sub Main()
        Dim dateValue As Date = #6/11/2008#
        Console.WriteLine(dateValue.DayOfWeek)
    End Sub
End Module
' The example displays the following output:
'    3

축약된 평일 이름 추출

  1. 정적 DateTime.Parse 또는 DateTimeOffset.Parse 메서드를 사용하여 날짜의 문자열 표현을 DateTime 또는 DateTimeOffset 값으로 변환합니다.

  2. 현재 문화권 또는 특정 문화권의 축약된 평일 이름을 추출할 수 있습니다.

    1. 현재 문화권의 축약된 요일 이름을 추출하려면 날짜 및 시간 값 DateTime.ToString(String) 또는 DateTimeOffset.ToString(String) 인스턴스 메서드를 호출하고 문자열 dddformat 매개 변수로 전달합니다. 다음 예제에서는 메서드에 대한 호출을 보여 줍니다 ToString(String) .

      using System;
      
      public class Example
      {
         public static void Main()
         {
            DateTime dateValue = new DateTime(2008, 6, 11);
            Console.WriteLine(dateValue.ToString("ddd"));
         }
      }
      // The example displays the following output:
       //       Wed
      
      Module Example
          Public Sub Main()
              Dim dateValue As Date = #6/11/2008#
              Console.WriteLine(dateValue.ToString("ddd"))
          End Sub
      End Module
      ' The example displays the following output:
      '       Wed
      
    2. 특정 문화권의 축약된 평일 이름을 추출하려면 날짜 및 시간 값 DateTime.ToString(String, IFormatProvider) 또는 DateTimeOffset.ToString(String, IFormatProvider) 인스턴스 메서드를 호출합니다. 문자열 ddd 을 매개 변수로 전달합니다 format . provider 매개 변수로 검색할 요일 이름이 포함된 문화권을 나타내는 CultureInfo 또는 DateTimeFormatInfo 개체를 전달합니다. 다음 코드는 fr-FR 문화를 나타내는 CultureInfo 개체를 사용하여 ToString(String, IFormatProvider) 메서드를 호출하는 방법을 보여 줍니다.

      using System;
      using System.Globalization;
      
      public class Example
      {
         public static void Main()
         {
            DateTime dateValue = new DateTime(2008, 6, 11);
            Console.WriteLine(dateValue.ToString("ddd",
                              new CultureInfo("fr-FR")));
         }
      }
      // The example displays the following output:
      //       mer.
      
      Imports System.Globalization
      
      Module Example
          Public Sub Main()
              Dim dateValue As Date = #6/11/2008#
              Console.WriteLine(dateValue.ToString("ddd",
                                New CultureInfo("fr-FR")))
          End Sub
      End Module
      ' The example displays the following output:
      '       mer.
      

전체 평일 이름 추출

  1. 정적 DateTime.Parse 또는 DateTimeOffset.Parse 메서드를 사용하여 날짜의 문자열 표현을 DateTime 값 또는 DateTimeOffset 값으로 변환합니다.

  2. 현재 문화권 또는 특정 문화권의 전체 평일 이름을 추출할 수 있습니다.

    1. 현재 문화권의 평일 이름을 추출하려면 날짜 및 시간 값 DateTime.ToString(String) 또는 DateTimeOffset.ToString(String) 인스턴스 메서드를 호출하고 문자열 ddddformat 매개 변수로 전달합니다. 다음 예제에서는 메서드에 대한 호출을 보여 줍니다 ToString(String) .

      using System;
      
      public class Example
      {
         public static void Main()
         {
            DateTime dateValue = new DateTime(2008, 6, 11);
            Console.WriteLine(dateValue.ToString("dddd"));
         }
      }
      // The example displays the following output:
      //       Wednesday
      
      Module Example
          Public Sub Main()
              Dim dateValue As Date = #6/11/2008#
              Console.WriteLine(dateValue.ToString("dddd"))
          End Sub
      End Module
      ' The example displays the following output:
      '       Wednesday
      
    2. 특정 문화권의 평일 이름을 추출하려면 날짜 및 시간 값 DateTime.ToString(String, IFormatProvider) 또는 DateTimeOffset.ToString(String, IFormatProvider) 인스턴스 메서드를 호출합니다. 문자열 dddd 을 매개 변수로 전달합니다 format . CultureInfoDateTimeFormatInfo 중 하나의 객체를 provider 매개 변수로 전달하여 검색할 평일 이름이 있는 문화권을 나타내도록 합니다. 다음 코드에서는 es-ES 문화권을 나타내는 개체를 사용하여 ToString(String, IFormatProvider) 메서드를 호출 CultureInfo 하는 방법을 보여 줍니다.

      using System;
      using System.Globalization;
      
      public class Example
      {
         public static void Main()
         {
            DateTime dateValue = new DateTime(2008, 6, 11);
            Console.WriteLine(dateValue.ToString("dddd",
                              new CultureInfo("es-ES")));
         }
      }
      // The example displays the following output:
      //       miércoles.
      
      Imports System.Globalization
      
      Module Example
          Public Sub Main()
              Dim dateValue As Date = #6/11/2008#
              Console.WriteLine(dateValue.ToString("dddd", _
                                New CultureInfo("es-ES")))
          End Sub
      End Module
      ' The example displays the following output:
      '       miércoles.
      

예시

다음 예제는 특정 날짜의 요일을 나타내는 숫자를 검색하기 위해 DateTime.DayOfWeekDateTimeOffset.DayOfWeek 속성을 호출하는 방법을 보여줍니다. DateTime.ToStringDateTimeOffset.ToString 메서드를 호출하여 약식 평일 이름과 전체 평일 이름을 추출하는 기능도 포함되어 있습니다.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string dateString = "6/11/2007";
      DateTime dateValue;
      DateTimeOffset dateOffsetValue;

      try
      {
         DateTimeFormatInfo dateTimeFormats;
         // Convert date representation to a date value
         dateValue = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
         dateOffsetValue = new DateTimeOffset(dateValue,
                                      TimeZoneInfo.Local.GetUtcOffset(dateValue));

         // Convert date representation to a number indicating the day of week
         Console.WriteLine((int) dateValue.DayOfWeek);
         Console.WriteLine((int) dateOffsetValue.DayOfWeek);

         // Display abbreviated weekday name using current culture
         Console.WriteLine(dateValue.ToString("ddd"));
         Console.WriteLine(dateOffsetValue.ToString("ddd"));

         // Display full weekday name using current culture
         Console.WriteLine(dateValue.ToString("dddd"));
         Console.WriteLine(dateOffsetValue.ToString("dddd"));

         // Display abbreviated weekday name for de-DE culture
         Console.WriteLine(dateValue.ToString("ddd", new CultureInfo("de-DE")));
         Console.WriteLine(dateOffsetValue.ToString("ddd",
                                                     new CultureInfo("de-DE")));

         // Display abbreviated weekday name with de-DE DateTimeFormatInfo object
         dateTimeFormats = new CultureInfo("de-DE").DateTimeFormat;
         Console.WriteLine(dateValue.ToString("ddd", dateTimeFormats));
         Console.WriteLine(dateOffsetValue.ToString("ddd", dateTimeFormats));

         // Display full weekday name for fr-FR culture
         Console.WriteLine(dateValue.ToString("ddd", new CultureInfo("fr-FR")));
         Console.WriteLine(dateOffsetValue.ToString("ddd",
                                                    new CultureInfo("fr-FR")));

         // Display abbreviated weekday name with fr-FR DateTimeFormatInfo object
         dateTimeFormats = new CultureInfo("fr-FR").DateTimeFormat;
         Console.WriteLine(dateValue.ToString("dddd", dateTimeFormats));
         Console.WriteLine(dateOffsetValue.ToString("dddd", dateTimeFormats));
      }
      catch (FormatException)
      {
         Console.WriteLine($"Unable to convert {dateString} to a date.");
      }
   }
}
// The example displays the following output:
//       1
//       1
//       Mon
//       Mon
//       Monday
//       Monday
//       Mo
//       Mo
//       Mo
//       Mo
//       lun.
//       lun.
//       lundi
//       lundi
Imports System.Globalization

Module Example
    Public Sub Main()
        Dim dateString As String = "6/11/2007"
        Dim dateValue As Date
        Dim dateOffsetValue As DateTimeOffset

        Try
            Dim dateTimeFormats As DateTimeFormatInfo
            ' Convert date representation to a date value
            dateValue = Date.Parse(dateString, CultureInfo.InvariantCulture)
            dateOffsetValue = New DateTimeOffset(dateValue, _
                                        TimeZoneInfo.Local.GetUtcOffset(dateValue))
            ' Convert date representation to a number indicating the day of week
            Console.WriteLine(dateValue.DayOfWeek)
            Console.WriteLine(dateOffsetValue.DayOfWeek)

            ' Display abbreviated weekday name using current culture
            Console.WriteLine(dateValue.ToString("ddd"))
            Console.WriteLine(dateOffsetValue.ToString("ddd"))

            ' Display full weekday name using current culture
            Console.WriteLine(dateValue.ToString("dddd"))
            Console.WriteLine(dateOffsetValue.ToString("dddd"))

            ' Display abbreviated weekday name for de-DE culture
            Console.WriteLine(dateValue.ToString("ddd", New CultureInfo("de-DE")))
            Console.WriteLine(dateOffsetValue.ToString("ddd", _
                                                       New CultureInfo("de-DE")))

            ' Display abbreviated weekday name with de-DE DateTimeFormatInfo object
            dateTimeFormats = New CultureInfo("de-DE").DateTimeFormat
            Console.WriteLine(dateValue.ToString("ddd", dateTimeFormats))
            Console.WriteLine(dateOffsetValue.ToString("ddd", dateTimeFormats))

            ' Display full weekday name for fr-FR culture
            Console.WriteLine(dateValue.ToString("ddd", New CultureInfo("fr-FR")))
            Console.WriteLine(dateOffsetValue.ToString("ddd", _
                                                       New CultureInfo("fr-FR")))

            ' Display abbreviated weekday name with fr-FR DateTimeFormatInfo object
            dateTimeFormats = New CultureInfo("fr-FR").DateTimeFormat
            Console.WriteLine(dateValue.ToString("dddd", dateTimeFormats))
            Console.WriteLine(dateOffsetValue.ToString("dddd", dateTimeFormats))
        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 to the console:
'       1
'       1
'       Mon
'       Mon
'       Monday
'       Monday
'       Mo
'       Mo
'       Mo
'       Mo
'       lun.
'       lun.
'       lundi
'       lundi

개별 언어는 .NET에서 제공하는 기능을 중복하거나 보완하는 기능을 제공할 수 있습니다. 예를 들어 Visual Basic에는 다음 두 가지 함수가 포함됩니다.

  • Weekday- 특정 날짜의 요일을 나타내는 숫자를 반환합니다. 첫 번째 날의 서수 값을 1로 간주하는 반면, DateTime.DayOfWeek 속성은 이를 0으로 간주합니다.

  • WeekdayName현재 문화권에서 특정 요일 번호에 해당하는 주의 이름을 반환하는 입니다.

다음 예제에서는 Visual Basic WeekdayWeekdayName 함수의 사용을 보여 줍니다.

Imports System.Globalization
Imports System.Threading

Module Example
    Public Sub Main()
        Dim dateValue As Date = #6/11/2008#

        ' Get weekday number using Visual Basic Weekday function
        Console.WriteLine(Weekday(dateValue))                 ' Displays 4
        ' Compare with .NET DateTime.DayOfWeek property
        Console.WriteLine(dateValue.DayOfWeek)                ' Displays 3

        ' Get weekday name using Weekday and WeekdayName functions
        Console.WriteLine(WeekdayName(Weekday(dateValue)))    ' Displays Wednesday

        ' Change culture to de-DE
        Dim originalCulture As CultureInfo = Thread.CurrentThread.CurrentCulture
        Thread.CurrentThread.CurrentCulture = New CultureInfo("de-DE")
        ' Get weekday name using Weekday and WeekdayName functions
        Console.WriteLine(WeekdayName(Weekday(dateValue)))   ' Displays Donnerstag

        ' Restore original culture
        Thread.CurrentThread.CurrentCulture = originalCulture
    End Sub
End Module

속성에서 반환된 DateTime.DayOfWeek 값을 사용하여 특정 날짜의 평일 이름을 검색할 수도 있습니다. 이 프로세스를 수행하려면 속성에서 반환된 값의 ToString 메서드 호출만 필요합니다. 그러나 이 기술은 다음 예제와 같이 현재 문화권에 대한 지역화된 평일 이름을 생성하지 않습니다.

using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Change current culture to fr-FR
      CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
      Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

      DateTime dateValue = new DateTime(2008, 6, 11);
      // Display the DayOfWeek string representation
      Console.WriteLine(dateValue.DayOfWeek.ToString());
      // Restore original current culture
      Thread.CurrentThread.CurrentCulture = originalCulture;
   }
}
// The example displays the following output:
//       Wednesday
Imports System.Globalization
Imports System.Threading

Module Example
    Public Sub Main()
        ' Change current culture to fr-FR
        Dim originalCulture As CultureInfo = Thread.CurrentThread.CurrentCulture
        Thread.CurrentThread.CurrentCulture = New CultureInfo("fr-FR")

        Dim dateValue As Date = #6/11/2008#
        ' Display the DayOfWeek string representation
        Console.WriteLine(dateValue.DayOfWeek.ToString())
        ' Restore original current culture
        Thread.CurrentThread.CurrentCulture = originalCulture
    End Sub
End Module
' The example displays the following output:
'       Wednesday

참고하십시오