Перейти к содержимому

Как выписать дни недели на си шарпе

  • автор:

Date Time. Day OfWeek Property

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Gets the day of the week represented by this instance.

public: property DayOfWeek DayOfWeek < DayOfWeek get(); >;
public DayOfWeek DayOfWeek
member this.DayOfWeek : DayOfWeek
Public ReadOnly Property DayOfWeek As DayOfWeek
Property Value

An enumerated constant that indicates the day of the week of this DateTime value.

Examples

The following example demonstrates the DayOfWeek property and the System.DayOfWeek enumeration.

// This example demonstrates the DateTime.DayOfWeek property using namespace System; int main() < // Assume the current culture is en-US. // Create a DateTime for the first of May, 2003. DateTime dt = DateTime(2003,5,1); Console::WriteLine( "Is Thursday the day of the week for ?: ", dt, dt.DayOfWeek == DayOfWeek::Thursday ); Console::WriteLine( "The day of the week for is .", dt, dt.DayOfWeek ); > /* This example produces the following results: Is Thursday the day of the week for 5/1/2003?: True The day of the week for 5/1/2003 is Thursday. */ 
// This example demonstrates the DateTime.DayOfWeek property open System // Assume the current culture is en-US. // Create a DateTime for the first of May, 2003. let dt = DateTime(2003, 5, 1) printfn $"Is Thursday the day of the week for ?: " printfn $"The day of the week for is ." // This example produces the following results: // // Is Thursday the day of the week for 5/1/2003?: True // The day of the week for 5/1/2003 is Thursday. 
// This example demonstrates the DateTime.DayOfWeek property using System; class Sample < public static void Main() < // Assume the current culture is en-US. // Create a DateTime for the first of May, 2003. DateTime dt = new DateTime(2003, 5, 1); Console.WriteLine("Is Thursday the day of the week for ?: ", dt, dt.DayOfWeek == DayOfWeek.Thursday); Console.WriteLine("The day of the week for is .", dt, dt.DayOfWeek); > > /* This example produces the following results: Is Thursday the day of the week for 5/1/2003?: True The day of the week for 5/1/2003 is Thursday. */ 
' This example demonstrates the DateTime.DayOfWeek property Class Sample Public Shared Sub Main() ' Assume the current culture is en-US. ' Create a DateTime for the first of May, 2003. Dim dt As New DateTime(2003, 5, 1) Console.WriteLine("Is Thursday the day of the week for ?: ", _ dt, dt.DayOfWeek = DayOfWeek.Thursday) Console.WriteLine("The day of the week for is .", dt, dt.DayOfWeek) End Sub End Class ' 'This example produces the following results: ' 'Is Thursday the day of the week for 5/1/2003?: True 'The day of the week for 5/1/2003 is Thursday. ' 

Remarks

The value of the constants in the DayOfWeek enumeration ranges from DayOfWeek.Sunday to DayOfWeek.Saturday. If cast to an integer, its value ranges from zero (which indicates DayOfWeek.Sunday) to six (which indicates DayOfWeek.Saturday).

The DayOfWeek property returns an enumerated constant; it does not reflect a system’s regional and language settings. To retrieve a string representing a localized weekday name for a particular date, call one of the overloads of the ToString method that includes a format parameter and pass it either the ddd or dddd custom format strings. For details, see How to: Extract the Day of the Week from a Specific Date.

Дни недели в C#

Как зная сегодняшнюю дату, узнать даты всех дней этой недели в c#? Также требуется получить даты всех дней месяца.

Отслеживать

94 4 4 бронзовых знака

задан 13 июн 2018 в 9:12

93 6 6 бронзовых знаков

13 июн 2018 в 9:34

Почитайте статью про DateTime metanit.com/sharp/tutorial/19.1.php

13 июн 2018 в 9:34

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

DateTime today = DateTime.Today; //Высчитываем начало недели var weekStart = today.AddDays(-(int)today.DayOfWeek + 1); //Высчитываем начало месяца var monthStart = today.AddDays(-today.Day + 1); var week = Enumerable.Range(0, 7).Select(count => weekStart.AddDays(count)).ToList(); var month = Enumerable.Range(0, DateTime.DaysInMonth(today.Year, today.Month)) .Select(count => monthStart.AddDays(count)).ToList(); 

В случае использования разных культур замените расчет начала недели на такой

var cultureStart = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; var weekStart = today; while (weekStart.DayOfWeek != cultureStart) weekStart = weekStart.AddDays(-1); 

Практическое руководство. Извлечение дня недели из конкретной даты

Платформа .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. Чтобы извлечь сокращенное имя дня недели для текущего языка и региональных параметров, вызовите метод или DateTimeOffset.ToString(String) экземпляр значения даты и времени DateTime.ToString(String) и передайте строку ddd в format качестве параметра . В следующем примере показан вызов 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 
    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. Чтобы извлечь имя дня недели для текущего языка и региональных параметров, вызовите метод или DateTimeOffset.ToString(String) экземпляр значения даты и времени DateTime.ToString(String) и передайте строку dddd в format качестве параметра . В следующем примере показан вызов 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 
      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.DayOfWeek свойств и DateTimeOffset.DayOfWeek для получения числа, представляющего день недели для определенной даты. Он также включает вызовы DateTime.ToString методов и DateTimeOffset.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 to a date.", dateString); > > > // 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 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 Weekday и WeekdayName :

      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 метода для значения, DayOfWeek возвращаемого свойством . Однако этот метод не создает локализованное имя дня недели для текущего языка и региональных параметров, как показано в следующем примере:

      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 

      См. также

      • Строки стандартных форматов даты и времени
      • Строки настраиваемых форматов даты и времени

      Совместная работа с нами на GitHub

      Источник этого содержимого можно найти на GitHub, где также можно создавать и просматривать проблемы и запросы на вытягивание. Дополнительные сведения см. в нашем руководстве для участников.

      Статья C# Как определить день недели по дате?

      Из этой статьи вы узнаете, как определять день недели по дате с помощью языка C#.

      1. Создадим новое консольное приложение (Console Application).

      using System; using System.Text; namespace example < class Program < static void Main(string[] args) < >> >

      2. Для определения дня недели воспользуемся классом DateTime.

      static void Main(string[] args) < DateTime dt = new DateTime(2014, 11, 1); Console.WriteLine(dt.ToString("dddd")); Console.ReadLine(); //Результат: суббота >

      Конструктор класса DateTime принимает 3 параметра: год, месяц и день месяца. Например, в данном примере я хочу узнать, какой день недели будет 1 ноября 2014 года.

      Получив объект типа DateTime (dt) определим день недели. Для этого либо воспользуемся свойством DayOfWeek, например:

      Console.WriteLine(dt.DayOfWeek); //Результат: Saturday

      Либо воспользуемся методом ToString, как например, в данном примере, указав в качестве параметра формат строки вида: “dddd”, который позволяет вывести полное название дня недели.

      Если нужно вывести сокращенное название (Пн, Вт, Ср. и т.д.), то в таком случае указываем формат:“ddd”.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

https://kapelnicza.vyvod-iz-zapoya-v-stacionare-samara12.ru/