Working with Dates

I have found that working with dates is a vital part of most scripting tasks. So here I will try and dig a little deeper and give some more information on the matter, so here goes...

Firstly Windows PowerShell Tip: More Fun with Dates (and Times) is a good article to get you started.

Date Formatting

With a bit of experimenting I have found the following:

  • dd - day of month, eg 04, 31
  • MM - month of year, eg 01, 11
  • yy - year, eg 08, 14
  • yyyy - year, eg 2008, 2014
  • hh - 12 hour, eg 09, 02
  • HH - 24 hour, eg, 09, 14
  • mm - minutes, eg 07, 53
  • ss - seconds, eg 06, 51
If in the format string you wish to output the letter h for example and you do not want it converted to an hour number then prefix it with a \ character.

There is a lot more detail on this at Windows PowerShell Tip: Formatting Dates and Times. it is also worth noting that you can do your "date arithmetic and formatting on one go as follows:
(Get-Date).AddDays(-1).ToString('dd-MM-yyyy'), which will display yesterday's date.
If you have a date/time in string format you can convert this to a date as follows:
Get-Date "16:11:23 1/8/14" -Format "yyyy-MM-dd HH:mm:ss", however this in effect converts it back to a string having re-formatted it. This can be done in two steps as follows:
$d = Get-Date "16:11:23 1/8/14"
Write-Host $d.ToString("yyyy-MM-dd HH:mm:ss")

Strange Date Formatting

Sometimes you might see US date formats coming out on a UK computer, even though you know the locale or language is set to the UK. Allow me to share something, first open up the PowerShell console and type the following:
Get-Date - which shows this: 21 December 2015 21:12:00
$StartTime = Get-Date
$StartTime
- 21 December 2015 21:12:05
All Good so far, but not try this:
Write-Host "$($StartTime)" - which shows: 12/21/2015 21:12:05, so why the US date?!
It seems there is a special case when casting a datetime object. In PowerShell (or .NET) it was decided that when casting a datetime object it should use a standard format, hence you get a US format, if you use the ToString() method then you get the UK locale and all is well.
Write-Host "$($StartTime.ToString())" - which shows 21/12/2015 21:12:05
So, a little wierd but true.

Date Differences

If you want to understand the difference between two dates then you need to execute the following:
New-TimeSpan -Start $StartTime - End $EndTime
This assumes you stored the output of something like Get-Date in $StartTime at the beginning an $EndTime at the end. If you store the output of "New-TimeSpan" then you can manipulate if and extract its properties like, Seconds and TotalSeconds, see New-TimeSpan for further details.