Date Time format displays differently in ISE and Windows Forms

风格不统一 提交于 2021-02-02 09:05:44

问题


When I run Get-Date in ISE, I get Wednesday, 15 April 2020 12:38:03 PM which I want.

However, if I run the same command in Windows Forms, I get 04/15/2020 12:38:03 in a different format.

I run them from the same computer so it must be the same cultural/region.


回答1:


1. Customizing your date using -Format or -UFormat

You can use the -Format or the -UFormat paramater to enforce a certain layout of your date:

Get-Date -Format "dddd, d MMMM yyyy hh:mm:ss tt"
Get-Date -UFormat "%A, %e %B %Y %r"

Both will display your desired date format, as long as you are using en-US culture information:

Wednesday, 15 April 2020 08:09:24 AM

Learn more about:

  • .NET format specifiers
  • UFormat specifiers

2. Customizing your date with different culture information

If you want to display the date in a different language, you can also enforce a certain culture information. Keep in mind that the -Format parameter is just a wrapper for the ToString() method. So you can also use the following line to display your date as desired:

(Get-Date).ToString('dddd, d MMMM yyyy hh:mm:ss tt')

Fortunately, there exist different overloads of that ToString() method. There is also one, that takes culture information as a second parameter. So in conclusion you can pass different culture info to your ToString() method to get results in different languages:

$culture = [System.Globalization.CultureInfo]::CreateSpecificCulture('en-US')
(Get-Date).ToString('dddd, d MMMM yyyy hh:mm:ss tt', $culture)

will display:

Wednesday, 15 April 2020 08:09:24 AM

and at the same time

$culture = [System.Globalization.CultureInfo]::CreateSpecificCulture('de-DE')
(Get-Date).ToString('dddd, d MMMM yyyy hh:mm:ss tt', $culture)

will display:

Mittwoch, 15 April 2020 08:09:24

3. Customizing your date with predefined culture specific patterns

In $culture.DateTimeFormat you can also find already prepared culture specific patterns to format your date and you can use them instead of writing them on your own:

$culture = [System.Globalization.CultureInfo]::CreateSpecificCulture('en-US')
(Get-Date).ToString($culture.DateTimeFormat.ShortDatePattern, $culture)

will display:

4/15/2020

and at the same time

$culture = [System.Globalization.CultureInfo]::CreateSpecificCulture('de-DE')
(Get-Date).ToString($culture.DateTimeFormat.ShortDatePattern, $culture)

will display:

15.04.2020

Btw: A similar pattern to yours, specified in your question, would be:

$culture = [System.Globalization.CultureInfo]::CreateSpecificCulture('en-US')
(Get-Date).ToString($culture.DateTimeFormat.FullDateTimePattern, $culture)

Wednesday, April 15, 2020 8:09:24 AM



来源:https://stackoverflow.com/questions/61220961/date-time-format-displays-differently-in-ise-and-windows-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!