Lavorare a settimane

Come tutti i programmatori che si misurano con schedulazioni di produzione, pianificazione delle spedizioni e chi più ne ha più ne metta mi trovo spesso a dover lavorare con le settimane al posto dei singoli giorni. Navigando un rete ho trovato questo thread da cui ho tratto ispirazione per la seguente classe.

Public Class Week

    ' Calculates the Week Number in accordance to ISO-8601 
    Public Shared Function GetNumber(ByVal dt As DateTime) As Integer 
        Dim year As Integer = dt.Year 
        Dim week1 As DateTime

        If dt >= New DateTime(year, 12, 29) Then 
            week1 = GetWeekOneDate(year + 1) 
            If dt < week1 Then 
                week1 = GetWeekOneDate(year) 
            End If 
        Else 
            week1 = GetWeekOneDate(year) 
            If dt < week1 Then 
                week1 = GetWeekOneDate(System.Threading.Interlocked.Decrement(year)) 
            End If 
        End If

        Return Math.Truncate((dt - week1).Days / 7 + 1) 
    End Function

    Private Shared Function GetWeekOneDate(ByVal year As Integer) As Date 
        ' Get the date for Jan-4 for the given year 
        Dim [date] As New Date(year, 1, 4)

        ' Get the ISO-8601 day number for this date 1==Monday, 7==Sunday 
        Dim dayNum As Integer = DirectCast([date].DayOfWeek, Integer) 
        ' 0==Sunday, 6==Saturday 
        If dayNum = 0 Then dayNum = 7

        ' Return the date of the Monday that is less than or equal to this date 
        Return [date].AddDays(1 - dayNum)

    End Function

    Public Shared Function GetStartingDay(ByVal dt As Date) As Date

        Dim dayNum As Integer = DirectCast(dt.DayOfWeek, Integer)


        If dayNum = 0 Then dayNum = 7

        Return dt.AddDays(1 - dayNum).Date

    End Function

    Public Overloads Shared Function ToString(ByVal dt As DateTime) As String

        Return dt.Year & "/" & GetNumber(dt).ToString("00")

    End Function

End Class

Sono alle "prime armi" con la strutturazione di soluzioni .NET per cui mi scuso se la soluzione non è "pulita"

A presto un post su una struttura che permette di lavorare con intervalli tra date.

Errata corrige: trovato un bug… ho corretto “Return Cint((dt - week1).Days / 7 + 1)” in “Return Math.Truncate((dt - week1).Days / 7 + 1)”

 

Technorati Tag: ,

posted @ mercoledì 2 luglio 2008 12:26

Print

Comments on this entry:

# Errata corrige: Lavorare a settimane

Left by DDL at 08/11/2008 14:15
Gravatar
Errata corrige: Lavorare a settimane

# Lavorare a settimane - Extension Methods

Left by DDL at 12/03/2013 16:58
Gravatar
Lavorare a settimane - Extension Methods
Comments have been closed on this topic.
«luglio»
domlunmarmergiovensab
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910