Friday 8 April 2011

Powershell: ISO Date Format

I've been looking to generate some database scripts on a regular basis and wanted to keep them in folders based upon date. As is my want, I like to keep the dates in ISO format so that they can be easily ordered through windows explorer.

The main problem I found using the DatePart functions in Powershell was that for the first 9days/months of the year, it returns just a single digit rather than padded with a zero (e.g 201148 rather than 20110408). I could have got round it with some extra string manipulation, but, a little bit of guidance from @theBoardz showed that you can just use the ToString() method on the get-date Cmdlet.

$dt = (get-date).ToString("yyyy" + (Get-date).ToString("mm" + (Get-date).ToString("dd"

UPDATE: can actually do this in a single line! Thanks Alan!

(get-date).ToString("yyyyMMdd")

2 comments:

  1. I find get-date -Format "yyyyMMdd" more readable; but perhaps that wasn't available in 2011?

    ReplyDelete

/* add this crazy stuff in so i can use syntax highlighter