从四月开始获得一周的周数

时间:2014-08-31 19:24:36

标签: c#

我目前正在使用此代码段:

private string GetCurrentWeek()
{
  // Return a string to be used in the TextBox control on the Main Form 
  DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
  int Year = DateTime.Now.Year;
  int Month = DateTime.Now.Month;
  int Day = DateTime.Now.Day;
  DateTime Date1 = new DateTime(Year, Month, Day);
  Calendar cal = dfi.Calendar;
  return cal.GetWeekOfYear(Date1, dfi.CalendarWeekRule, dfi.FirstDayOfWeek).ToString();
 }

获取当年的当前一周。哪个按预期返回。虽然。这是从1月开始。这是代码所说的。虽然,我理想地从四月开始寻找它。因此,第1周将于4月6日开始,第52周将于4月5日开始(就像英国税务年度一样)。我已经寻求互联网和谷歌(可能使用错误的关键字),但我无法发现如何使用C#执行此任务

1 个答案:

答案 0 :(得分:3)

我假设您希望第1周始终在4月6日开始,并且长达7天,而不是像#34周一那样的规则;周总是从星期一开始#34;。基本上这只是一个问题:

  • 确定
  • 中的哪个纳税年度
  • 查找该纳税年度的开始
  • 从当前日期减去该日期
  • 将结果除以7

例如:

DateTime today = DateTime.Today;
int taxYear = today.Month > 4 || today.Month == 4 && today.Day >= 6
    ? today.Year : today.Year - 1;
DateTime taxYearStart = new DateTime(taxYear, 4, 6);
TimeSpan elapsedTaxYear = today - taxYearStart;
int days = elapsedTaxYear.Days;
int taxYearWeek = (days / 7) + 1;

当然,您也可以使用Noda Time

// Usually inject this, using SystemClock.Instance for production
IClock clock = ...; 
// For the UK, use DateTimeZoneProviders.Tzdb["Europe/London"];
DateTimeZone zone = ...; 
// This will be simpler in Noda Time 2.0 with ZonedClock
LocalDate today = clock.Now.InZone(zone).LocalDateTime.Date;

int taxYear = today.Month > 4 || today.Month == 4 && today.Day >= 6
    ? today.Year : today.Year - 1;
LocalDate taxYearStart = new LocalDate(taxYear, 4, 6);
int days = Period.Between(taxYearStart, today, PeriodUnits.Days).Days;
int taxYearWeek = (days / 7) + 1;