Format a Date for Output

1. Problem

You want to control the way that PowerShell displays or formats a date.

2. Solution

To control the format of a date, use one of the following options:

The Get-Date cmdlet’s –Format parameter:

PS >Get-Date -Date "05/09/1998 1:23 PM" -Format "dd-MM-yyyy @ hh:mm:ss"
09-05-1998 @ 01:23:00

PowerShell’s string formatting (–f) operator:

PS >$date = [DateTime] "05/09/1998 1:23 PM"
PS >"{0:dd-MM-yyyy @ hh:mm:ss}" -f $date
09-05-1998 @ 01:23:00

The object’s ToString() method:

PS >$date = [DateTime] "05/09/1998 1:23 PM"
PS >$date.ToString("dd-MM-yyyy @ hh:mm:ss")
09-05-1998 @ 01:23:00

The Get-Date cmdlet’s–UFormat parameter, which supports Unix date format strings:

PS >Get-Date -Date "05/09/1998 1:23 PM" -UFormat "%d-%m-%Y @ %I:%M:%S"
09-05-1998 @ 01:23:00

3. Discussion

Except for the–Uformat parameter of the Get-Date cmdlet, all date formatting in PowerShell uses the standard .NET DateTime format strings. These format strings let you display dates in one of many standard formats (such as your system’s short or long date patterns), or in a completely custom manner. For more information on how to specify standard .NET DateTime format strings, see Appendix I, .NET DateTime Formatting.

If you are already used to the Unix-style date formatting strings (or are converting an existing script that uses a complex one), the–Uformat parameter of the Get-Date cmdlet may be helpful. It accepts the format strings accepted by the Unix date command, but does not provide any functionality that standard .NET date formatting strings cannot.

When working with the string version of dates and times, be aware that they are the most common source of internationalization issues—problems that arise from running a script on a machine with a different culture than the one it was written on. In North America “05/09/1998″ means “May 9, 1998.” In many other cultures, though, it means “September 5, 1998.” Whenever possible use and compare DateTime objects (rather than strings) to other DateTime objects, as that avoids these cultural differences. Example 5-6 demonstrates this approach.

Example 5-6. Comparing DateTime objects with the -gt operator
PS >$dueDate = [DateTime] "01/01/2006"
PS >if([DateTime]::Now -gt $dueDate)
>> {
>>     "Account is now due"
>> }
>> 
Account is now due

PowerShell always assumes the North American date format when it interprets a DateTime constant such as [DateTime] “05/09/1998″. This is for the same reason that all languages interpret numeric constants (such as 12.34) in the North American format. If it did otherwise, nearly every script that dealt with dates and times would fail on international systems.

For more information about the Get-Date cmdlet, type Get-Help Get-Date.

Tags: , , , , , , , , , , , ,