.NET mi dà il numero della settimana sbagliato per il 29 dicembre 2008?
-
06-07-2019 - |
Domanda
Secondo calendario ufficiale (gregoriano) , il numero della settimana per il 29/12/2008 è 1, perché dopo l'ultimo giorno della settimana 52 (ovvero il 28/12) sono rimasti tre o meno giorni nell'anno . Un po 'strane, ma OK, le regole sono regole.
Quindi, secondo questo calendario, abbiamo questi valori limite per il 2008/2009
- 28/12 è la settimana 52
- 29/12 è la settimana 1
- 1/1 è la settimana 1
- 8/1 è la settimana 2
C # offre una classe GregorianCalendar, che ha una funzione GetWeekOfYear (data, regola, firstDayOfWeek)
.
Il parametro rule
è un'enumerazione con 3 possibili valori: FirstDay, FirstFourWeekDay, FirstFullWeek
. Da quello che ho capito dovrei scegliere la regola FirstFourWeekDay
, ma ho provato tutti loro per ogni evenienza.
L'ultimo parametro indica quale giorno della settimana dovrebbe essere considerato il primo giorno della settimana, secondo quel calendario è lunedì, quindi lunedì.
Quindi ho avviato un'app console sporca e veloce per testare questo:
using System;
using System.Globalization;
namespace CalendarTest
{
class Program
{
static void Main(string[] args)
{
var cal = new GregorianCalendar();
var firstWeekDay = DayOfWeek.Monday;
var twentyEighth = new DateTime(2008, 12, 28);
var twentyNinth = new DateTime(2008, 12, 29);
var firstJan = new DateTime(2009, 1, 1);
var eightJan = new DateTime(2009, 1, 8);
PrintWeekDays(cal, twentyEighth, firstWeekDay);
PrintWeekDays(cal, twentyNinth, firstWeekDay);
PrintWeekDays(cal, firstJan, firstWeekDay);
PrintWeekDays(cal, eightJan, firstWeekDay);
Console.ReadKey();
}
private static void PrintWeekDays(Calendar cal, DateTime dt, DayOfWeek firstWeekDay)
{
Console.WriteLine("Testing for " + dt.ToShortDateString());
Console.WriteLine("--------------------------------------------");
Console.Write(CalendarWeekRule.FirstDay.ToString() + "\t\t");
Console.WriteLine(cal.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, firstWeekDay));
Console.Write(CalendarWeekRule.FirstFourDayWeek.ToString() + "\t");
Console.WriteLine(cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, firstWeekDay));
Console.Write(CalendarWeekRule.FirstFullWeek.ToString() + "\t\t");
Console.WriteLine(cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFullWeek, firstWeekDay));
Console.WriteLine("--------------------------------------------");
}
}
}
... e questo è quello che ottengo
Testing for 28.12.2008
--------------------------------------------
FirstDay 52
FirstFourDayWeek 52
FirstFullWeek 51
--------------------------------------------
Testing for 29.12.2008
--------------------------------------------
FirstDay 53
FirstFourDayWeek 53
FirstFullWeek 52
--------------------------------------------
Testing for 01.01.2009
--------------------------------------------
FirstDay 1
FirstFourDayWeek 1
FirstFullWeek 52
--------------------------------------------
Testing for 08.01.2009
--------------------------------------------
FirstDay 2
FirstFourDayWeek 2
FirstFullWeek 1
--------------------------------------------
Quindi, come vediamo, nessuna delle combinazioni precedenti corrisponde al calendario ufficiale (se hai fretta, vedi che il 29/12 non ottiene mai la settimana n. 1).
Cosa sto sbagliando qui? Forse c'è qualcosa di eclatante che mi manca? (è venerdì e l'orario di lavoro tardivo qui in Belgio, abbiate pazienza;))
Modifica: forse dovrei spiegare: ciò di cui ho bisogno è una funzione che funzioni per qualsiasi anno, restituendo gli stessi risultati del calendario gregoriano che ho collegato. Quindi nessuna soluzione alternativa speciale per il 2008.
Soluzione
Questo articolo esamina più a fondo il problema e le possibili soluzioni alternative. Il fulcro della questione è che l'implementazione del calendario .NET non sembra implementare fedelmente lo standard ISO
Altri suggerimenti
@Conrad è corretto. L'implementazione .NET di DateTime e GregorianCalendar non implementano / seguono le specifiche ISO 8601 complete. Detto questo, le specifiche sono estremamente dettagliate e non banali da attuare pienamente, almeno per il lato dell'analisi delle cose.
Ulteriori informazioni sono disponibili sui seguenti siti:
- http://www.iso.org/iso /en/prods-services/popstds/datesandtime.html
- http://www.w3.org/TR/NOTE-datetime
- http://www.cl.cam.ac. uk / ~ mgk25 / iso-time.html
- http://www.cs.tut.fi/~jkorpela/iso8601 .html
- http://hydracen.com/dx/iso8601.htm
- http://www.probabilityof.com/ISO8601.shtml
- http: //www.mcs .vuw.ac.nz tecnico / / software / SGML / doc / ISO8601 / ISO8601.html |
In poche parole:
Una settimana è identificata dal suo numero in un determinato anno e inizia con un lunedì. La prima settimana di un anno è quella che include il primo giovedì, o equivalentemente quella che include il 4 gennaio.
Ecco una parte del codice che uso per gestire correttamente le date ISO 8601:
#region FirstWeekOfYear
/// <summary>
/// Gets the first week of the year.
/// </summary>
/// <param name="year">The year to retrieve the first week of.</param>
/// <returns>A <see cref="DateTime"/>representing the start of the first
/// week of the year.</returns>
/// <remarks>
/// Week 01 of a year is per definition the first week that has the Thursday
/// in this year, which is equivalent to the week that contains the fourth
/// day of January. In other words, the first week of a new year is the week
/// that has the majority of its days in the new year. Week 01 might also
/// contain days from the previous year and the week before week 01 of a year
/// is the last week (52 or 53) of the previous year even if it contains days
/// from the new year.
/// A week starts with Monday (day 1) and ends with Sunday (day 7).
/// </remarks>
private static DateTime FirstWeekOfYear(int year)
{
int dayNumber;
// Get the date that represents the fourth day of January for the given year.
DateTime date = new DateTime(year, 1, 4, 0, 0, 0, DateTimeKind.Utc);
// A week starts with Monday (day 1) and ends with Sunday (day 7).
// Since DayOfWeek.Sunday = 0, translate it to 7. All of the other values
// are correct since DayOfWeek.Monday = 1.
if (date.DayOfWeek == DayOfWeek.Sunday)
{
dayNumber = 7;
}
else
{
dayNumber = (int)date.DayOfWeek;
}
// Since the week starts with Monday, figure out what day that
// Monday falls on.
return date.AddDays(1 - dayNumber);
}
#endregion
#region GetIsoDate
/// <summary>
/// Gets the ISO date for the specified <see cref="DateTime"/>.
/// </summary>
/// <param name="date">The <see cref="DateTime"/> for which the ISO date
/// should be calculated.</param>
/// <returns>An <see cref="Int32"/> representing the ISO date.</returns>
private static int GetIsoDate(DateTime date)
{
DateTime firstWeek;
int year = date.Year;
// If we are near the end of the year, then we need to calculate
// what next year's first week should be.
if (date >= new DateTime(year, 12, 29))
{
if (date == DateTime.MaxValue)
{
firstWeek = FirstWeekOfYear(year);
}
else
{
firstWeek = FirstWeekOfYear(year + 1);
}
// If the current date is less than next years first week, then
// we are still in the last month of the current year; otherwise
// change to next year.
if (date < firstWeek)
{
firstWeek = FirstWeekOfYear(year);
}
else
{
year++;
}
}
else
{
// We aren't near the end of the year, so make sure
// we're not near the beginning.
firstWeek = FirstWeekOfYear(year);
// If the current date is less than the current years
// first week, then we are in the last month of the
// previous year.
if (date < firstWeek)
{
if (date == DateTime.MinValue)
{
firstWeek = FirstWeekOfYear(year);
}
else
{
firstWeek = FirstWeekOfYear(--year);
}
}
}
// return the ISO date as a numeric value, so it makes it
// easier to get the year and the week.
return (year * 100) + ((date - firstWeek).Days / 7 + 1);
}
#endregion
#region Week
/// <summary>
/// Gets the week component of the date represented by this instance.
/// </summary>
/// <value>The week, between 1 and 53.</value>
public int Week
{
get
{
return this.isoDate % 100;
}
}
#endregion
#region Year
/// <summary>
/// Gets the year component of the date represented by this instance.
/// </summary>
/// <value>The year, between 1 and 9999.</value>
public int Year
{
get
{
return this.isoDate / 100;
}
}
#endregion
I numeri delle settimane differiscono da paese a paese e dovrebbero dipendere dalle impostazioni locali / regionali se non sbaglio del tutto.
Modifica: Wikipedia supporta il mio vago ricordo che questi numeri differiscono in base al paese: http: // en.wikipedia.org/wiki/Week_number#Week_number
Mi aspetterei che una struttura rispettabile obbedisca al PAESE selezionato nel runtime locale.
Nella mia esperienza, il comportamento dimostrato è il comportamento tipico, riferito alla settimana finale parziale come settimana 53. Ciò può essere dovuto al fatto che tutta l'esposizione significativa che ho avuto ai numeri delle settimane è stata correlata alla contabilizzazione della fine dell'anno civile a fini di reportistica e l'IRS (o l'agenzia fiscale di tua scelta) considera che l'anno civile si concluderà il 31 dicembre, non l'ultima settimana completa dell'anno.
So che questo è un vecchio post, ma in ogni caso il tempo di noda sembra ottenere il risultato corretto ..
Come soluzione, potresti dire che il numero della settimana è WeekNumber mod 52. Credo che questo funzionerebbe per i casi che descrivi.
Come soluzione alternativa, perché non utilizzare FirstFourDayWeek
ma aggiungere:
if ( weekNumber > 52 )
weekNumber = 1;