用日期和月份的日期计算CalenderWeek

时间:2019-11-22 08:46:09

标签: c#

我在C#中进行了一次练习,我必须输入日期和月份(例如6.4),然后计算“日历周”。所以我在互联网上搜索,但什么也没找到。而且,从星期一开始的一年也更容易。

Console.WriteLine("Bitte Tag eingeben");
int day = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Bitte Monat eingeben");
int month = Convert.ToInt32(Console.ReadLine());

calender(day, month);

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用Calendar.GetWeekOfYear,尽管这也需要输入年份:

Console.WriteLine("Bitte Tag eingeben");
int day = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Bitte Monat eingeben");
int month = Convert.ToInt32(Console.ReadLine());

DateTime dt = new DateTime(2019, month, day);

CultureInfo culture = CultureInfo.CurrentCulture;
CalendarWeekRule cwr = culture.DateTimeFormat.CalendarWeekRule;
DayOfWeek dow = culture.DateTimeFormat.FirstDayOfWeek;

int weekOfYear = culture.Calendar.GetWeekOfYear(dt, cwr, dow);

话虽如此,在没有年份的情况下(假设不是a年),构造手动计算并不难:

// Construct an array, with month as index and days as value
int[] monthDays = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Count the number of days up to the given month
int days = 0;
for (int i = 0; i < month - 1; i++)
{
    days += monthDays[i];
}

// Add the given number of days
days += day

// Divide by 7 to get the week of the year
int weekOfYear = (int)Math.Ceiling((double)days / 7);

当然,如果是a年,则需要将数组修改为new int[] { 31, 29, ...