问题
I want to find a date are now on week number with c# desktop Application.
I've been looking on google, but none that fit my needs.
How do I get a week in a month as the example below?
Example:
I want January 6, 2014 = the first week of January
January 30, 2014 = fourth week
of January
but 1 February 2014 = week 4 in January
and 3 February 2014 was the first week in February
回答1:
Here is the method:
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;
}
Test:
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 6))); // 1
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 30))); // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 1))); // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 3))); // 1
回答2:
public static int GetWeekNumber(DateTime dt)
{
CultureInfo curr= CultureInfo.CurrentCulture;
int week = curr.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return week;
}
回答3:
The method will return a structure with the first and last date of that quarter.
private String test()
{
DateRangeStruct retVal;
retVal.startDate = retVal.endDate = Now;
retVal = DateRange(DateRangeOptions.Week, DateTime.Today);
}
please refer these link http://nonsequiturs.com/articles/find-the-first-and-last-day-of-a-date-range-using-c-and-asp-net/
回答4:
I think this is what you want:
public static int GetWeekOfMonth(DateTime date)
{
DateTime beginningOfMonth = new DateTime(date.Year, date.Month, 1);
while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
date = date.AddDays(1);
return (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;
}
Its authored by David M Morton on http://social.msdn.microsoft.com/Forums/vstudio/en-US/bf504bba-85cb-492d-a8f7-4ccabdf882cb/get-week-number-for-month
来源:https://stackoverflow.com/questions/23060121/get-week-of-month-c-sharp