Getting Week number of year starting from April

2019-08-10 21:21发布

I'm currently using this snippet:

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();
 }

To get the current week of the year. Which returns as expected. Though. This is starting from January. Which is doing what the code says. Though, I'm ideally looking for it to start from April. So week 1 would start on the 6th of April and Week 52 would be on April 5th (just like the UK Tax Year). I have sought the internet and google (perhaps using wrong keywords) but I'm unable to discover how to perform this task using C#

标签: c#
1条回答
Rolldiameter
2楼-- · 2019-08-10 21:32

I'm assuming you want week 1 to begin on April 6th always, and be 7 days long, rather than having some rule like "Weeks always start on Mondays". Basically this is just a matter of:

  • Working out which tax year you're in
  • Finding the start of that tax year
  • Subtracting that date from the current date
  • Dividing the result by 7

For example:

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;

Of course, you could also use 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;
查看更多
登录 后发表回答