我怎样才能找出一个月中的第几天?
how can I find out the day of the month?
我必须找出给定日期的日期,假设我有 01/26/2020 日期,现在日期 26 是该月的第 4 个星期日,我如何通过它的可重复计数找出日期在一个月内?
没有直接实现的方法that.You需要调用类似下面的代码
DateTime dateValue = new DateTime(2019, 12, 19);
int getDayOfWeek = GetWeekNumberOfMonth(dateValue);
//convert to ordinal
string ordinalWeekOfMonth = AddOrdinal(getDayOfWeek);
Console.WriteLine(ordinalWeekOfMonth + " " + dateValue.DayOfWeek);//output like 2nd sunday
下面的依赖方法可以用来调用上面的代码
public static int GetWeekNumberOfMonth(DateTime date)
{
date = date.Date;
DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
if (firstMonthMonday > date)
{
firstMonthDay = firstMonthDay.AddMonths(-1);
firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
}
return (date - firstMonthMonday).Days / 7 + 1;
}
public static string AddOrdinal(int num)
{
if (num <= 0) return num.ToString();
switch (num % 100)
{
case 11:
case 12:
case 13:
return num + "th";
}
switch (num % 10)
{
case 1:
return num + "st";
case 2:
return num + "nd";
case 3:
return num + "rd";
default:
return num + "th";
}
}
我必须找出给定日期的日期,假设我有 01/26/2020 日期,现在日期 26 是该月的第 4 个星期日,我如何通过它的可重复计数找出日期在一个月内?
没有直接实现的方法that.You需要调用类似下面的代码
DateTime dateValue = new DateTime(2019, 12, 19);
int getDayOfWeek = GetWeekNumberOfMonth(dateValue);
//convert to ordinal
string ordinalWeekOfMonth = AddOrdinal(getDayOfWeek);
Console.WriteLine(ordinalWeekOfMonth + " " + dateValue.DayOfWeek);//output like 2nd sunday
下面的依赖方法可以用来调用上面的代码
public static int GetWeekNumberOfMonth(DateTime date)
{
date = date.Date;
DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
if (firstMonthMonday > date)
{
firstMonthDay = firstMonthDay.AddMonths(-1);
firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
}
return (date - firstMonthMonday).Days / 7 + 1;
}
public static string AddOrdinal(int num)
{
if (num <= 0) return num.ToString();
switch (num % 100)
{
case 11:
case 12:
case 13:
return num + "th";
}
switch (num % 10)
{
case 1:
return num + "st";
case 2:
return num + "nd";
case 3:
return num + "rd";
default:
return num + "th";
}
}