tplive
tplive

Reputation: 735

PowerShell date format not behaving

I'm stumped. :)

My computer has PowerShell 5.1 installed. On another computer (same language) 5.0 it works as expected. (Check using Get-Culture; my locale is nb-NO (Norwegian) )

Consider this:

Get-Date

returns

tirsdag 23. mai 2017 13.13.18

So I do this

Get-Date -Format "H-m-s"

as expected it returns

13-13-18

But then I do this

Get-Date -Format "H:m:s"

You think it returns

13:13:18

right? (it does on PS5.0!) No! I get this:

13.13.18

Only if I do this, is the output what I want:

Get-Date -Format "H\:m\:s"
13:13:18

Can someone please explain why this is? I discovered it "by accident" when I wanted to format a datetime-compatible string for use in SQL Server.

Upvotes: 1

Views: 565

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

That's because the underlying DateTime formatting function see's : and treats it as a culture-dependent "time separator".

In Norwegian (no-NO), the default time separator is .. You can inspect this with (assuming that no-NO is the current culture):

PS C:\> [CultureInfo]::CurrentCulture.DateTimeFormat.TimeSeparator
.

You can also override this, either by inserting a literal :, with the escape sequence \: as you've already found, or you can override it globally (for the lifetime of the current process/appdomain):

PS C:\> [CultureInfo]::CurrentCulture.DateTimeFormat.TimeSeparator = ":"
PS C:\> Get-Date -Format "H:m:s"
13:13:18

Upvotes: 1

Related Questions