Earlier this week I was having some fun with @EnergizedTech on Twitter, playing around with dates in PowerShell. I'm not even sure where we started but the experience got me thinking and it's Friday so let's have some fun.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
While I can easily find out what the day of the year is for a given date:
([datetime]"7/4/2013").dayOfYear
there's no method to convert an integer to a day of the year. But it really isn't that hard. Here's a simple function.
<# .Synopsis Get day of year .Description Get the day of the year for a given integer. The default year is the current. #> [cmdletbinding()] Param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Enter an integer for the day of the year.")] [ValidateRange(1,366)] [int]$DayOfYear, [ValidateRange(1,9999)] [int]$Year=(Get-Date).Year ) #define the first day of the year [datetime]$dt= "1/1/$Year" #the smart way $dt.AddDays($DayOfYear-1) <# Ignore this. It is the "hard" way. I clearly was overthinking this. #loop through each day of the year and compare it to the target day of the year While ( $dt.DayOfyear -ne $dayofYear) { $dt = $dt.AddDays(1) } #write the final date $dt.Date #> } #close function
The stuff around the command is longer than the command itself. But I don't mind. The function takes an integer value between 1 and 366, the most possible days in a year. You can also specify a year, but it defaults to the current year. The function then loops using a While loop which keeps adding one day to until the day of the year matches the target day of the year. I used a While loop because it is possible that the expression will be True immediately and there's no need to process the scriptblock. Copy and paste the code and try for yourself!
UPDATE: I knew as soon as I posted that someone would show me a better way. And they did. I was clearly overthinking the problem. I've updated the code to show the smart way to do this. And now the solution is so short, you probably don't even need the function.
Like this:
For day 301
([datetime]’1/1/2013′).AddDays(301-1)
Have to subtract 1 but it eliminates the loop
I see now. I knew that as soon as I posted this that someone (probably you) would point out a better, and this case obvious way.
Ha. I knew you would see it I should have not posted and waited to see how long before you got a brain tickle.
Nice little Friday morsel. Have a great weekend.