using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GPW.CORE.Data { public class WeekData { public int anno { get; set; } = DateTime.Today.Year; public DateTime inizio { get; set; } = DateTime.Today; public DateTime fine { get; set; } = DateTime.Today.AddDays(1); public int weekNumber { get; set; } = 1; /// /// Calcola estremi settimana dato un giorno come lunedì-domenica /// /// public WeekData(DateTime dtRif) { DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(dtRif); this.anno = dtRif.Year; this.weekNumber = GetIso8601WeekOfYear(dtRif); this.inizio = dtRif.Date.AddDays(1 - (int)day); this.fine = dtRif.Date.AddDays(7 - (int)day); } /// /// Calcola estremi settimana dato numero + anno /// /// public WeekData(int year, int numWeek) { this.anno = year; this.weekNumber = numWeek; DateTime dtRif = new DateTime(year, 1, 4).AddDays(7 * numWeek); DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(dtRif); this.inizio = dtRif.Date.AddDays(1 - (int)day); this.fine = dtRif.Date.AddDays(7 - (int)day); } /// /// Calcolo settimana dell'anno ISO 8601 /// /// This presumes that weeks start with Monday. /// Week 1 is the 1st week of the year with a Thursday in it. /// /// rif: https://stackoverflow.com/questions/11154673/get-the-correct-week-number-of-a-given-date /// /// /// public static int GetIso8601WeekOfYear(DateTime time) { // Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll // be the same week# as whatever Thursday, Friday or Saturday are, // and we always get those right DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { time = time.AddDays(3); } // Return the week of our adjusted day return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } } }