Some systems I work with require dates in the form YYYYDDD, where DDD is the number of days since the beginning of the year. For example, Feb 1, 2009 is the 32 day from the start of the year, 2009032.
Here is a PowerShell function to calculate and format the result. A few things it demonstrates, using a ‘formula’ in the range operator, a begin/process/end block in a ForEach and using the current object ($_) to do a lookup in a hash table.
The Code
Function Get-NumberOfDaysToDate ([datetime]$date=(Get-Date)) {
$DaysInMonthByNumber = @{
1 = 31
2 = 28
3 = 31
4 = 30
5 = 31
6 = 30
7 = 31
8 = 31
9 = 30
10 = 31
11 = 30
12 = 31
}
0..($date.ToString("MM")-1) |
ForEach `
{ $sum=0 } `
{ $sum+=$DaysInMonthByNumber.$_ } `
{ "{0}{1:0##}" -f $date.Year, ($sum+$date.Day) }
}
{ 5 comments… read them below or add one }
Perhaps using the $date.DayOfYear property would remove the need for a hashtable of the number of days in each month.
Regards,
Jason
You can simplify it to:
PS > “{0}{1:0##}” -f $date.year,$date.dayofyear
2009001
PS >”{0}{1:0##}” -f $date.year,$date.dayofyear
2009166
By the way, you can create the $DaysInMonthByNumber hashtable programatically:
$DaysInMonthByNumber = 1..12 | foreach -begin {$daysInMonth=@{}} -process { $daysInMonth.$_ = [datetime]::DaysInMonth($date.year,$_) } -end {$daysInMonth}
That will be accurate 79% of the time.
Thank you, I should have put that at the beginning. I wanted to show Hash tables, for loops and aggregation.
Is the hash necessary? This one-liner gives you the total # of day since the beginning of the current year:
([System.DateTime]::Now – (new-object System.DateTime ([System.DateTime]::Now.Year,1,1))).TotalDays