PowerShell: How to Calculate the Number of Days from the Beginning of the Year

by Doug Finke on November 23, 2009

in PowerShell

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.

image

image

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 }

Jason Stangroome 11.24.09 at 12:18 am

Perhaps using the $date.DayOfYear property would remove the need for a hashtable of the number of days in each month.

Regards,

Jason

Shay Levy 11.24.09 at 5:10 am

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}

Andy Bryant 11.24.09 at 9:11 am

That will be accurate 79% of the time.

Doug Finke 11.24.09 at 10:20 am

Thank you, I should have put that at the beginning. I wanted to show Hash tables, for loops and aggregation.

@xcud 11.24.09 at 10:34 am

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

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>