So the other day I was presented with the issue of converting a Julian Date (YYYYDDD) to a Gregorian Date (MMDDYYYY). After a few minutes in Powershell I realized that there was no built in way to do this. A few minutes a Googling yielded a few long, bloated scripts. I knew there had to be a better way, and there is!
1 2 3 4 5 6 7 8 9 |
# Set our Julian Date to the 120th day of 2015 $JulianDate = "2015120" # Now separate the year and day of the year into their own variables $JulianYear = $JulianDate.Substring(0,4) $JulianDay = $JulianDate.Substring(4,3) # Lastly, get a DateTime object for our date using .AddDays() to start at Jan 1 and add n-1 days to it $GregorianDate = (Get-Date -Year $JulianYear -Month 01 -Day 01 -Hour 0 -Minute 0 -Second 1).AddDays($JulianDay - 1) |
Now we have a nice DateTime Object in our familiar Gregorian format. Useful for converting Julian dates in filenames or headers.
1 2 3 |
PS D:\> $GregorianDate Thursday, April 30, 2015 12:00:01 AM |
In a production setting you would definitely want to add some data validation to make sure the year is valid, the $JulianDay is a valid number between 1 and 365 (or 366 on a leap year), and so on. Hope this helps, and happy scripting!