Roger Clerkwell
Roger Clerkwell

Reputation: 426

Powershell change a date to dd/mm/yyyy hh:ss format and then to string

I have a string field containing a date '2020-11-03 17:38:59.0'

I'm trying to convert it to date format dd/mmm/yyyy hh:mm and then back to string.

I'm trying this which I have cobbled together reading on the internet

    $DateFormatChange = [datetime]::ParseExact('2020-11-03 17:38:59.0', 'yyyy-M-dd HH:mm:ss.f', $null).ToString('dd/mm/yyyy hh:mm')

but it is giving me a strange result of 03/38/2020 05:38

Upvotes: 2

Views: 7795

Answers (1)

marsze
marsze

Reputation: 17055

Your format string does not do what you think it does. "hh" is the hour in 12-hour format and "mm" is minutes (not months). Have a look at the .NET documentation Custom date and format strings.

You will see that format-strings are case-sensitive, so you might accidentally get the wrong result if you don't pay attention to that.

Some examples:

"hh" The hour, using a 12-hour clock from 01 to 12.

"HH" The hour, using a 24-hour clock from 00 to 23.

"mm" The minute, from 00 through 59.

"MM" The month, from 01 through 12.

So, the correct format would be:

.ToString('dd/MM/yyyy HH:mm')

Also, I recommend to specify the culture. Otherwise the result will also be influenced by the thread-culture. / and : are treated as part of the format specifier, not as literal characters. (See the Notes section.) For example, with a German culture, "dd/MM/yyyy" would result in "03.11.2020", not "03/11/2020".

Use InvariantCulture:

.ToString('dd/MM/yyyy HH:mm', [System.Globalization.CultureInfo]::InvariantCulture)

Upvotes: 3

Related Questions