PowerTip: Use PowerShell to Create a Date String

PowerTip: Use PowerShell to Create a Date String

  • Comments 8
  • Likes

Summary: Use Windows PowerShell to create a date string that has a month, day, and year.

Hey, Scripting Guy! Question How can I use Windows PowerShell to create a string that represents the date with the month, day, and year?

Hey, Scripting Guy! Answer Feed a pattern of ‘M/d/y’ to the ToString method from Get-Date:

PS C:\> (get-date).ToString('M/d/y')

10/28/13

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Thank You for sharing another great tip.

    Alternative way to generate short date string from datetime:

    (Get-Date).ToString("d")  # nothing new ;)

    but overloaded ToString method supports culture-specific format:

    PS C:\> $frfr = 'fr-FR' -as [Globalization.CultureInfo]

    $frca = 'fr-CA' -as [Globalization.CultureInfo]

    $dede = 'de-DE' -as [Globalization.CultureInfo]

    (Get-Date).ToString("d",$frfr)

    (Get-Date).ToString("d",$frca)

    (Get-Date).ToString("d",$dede)

    08/11/2013

    2013-11-08

    08.11.2013

  • @JacekZ I am glad you like the tip. Thanks for sharing your overloads for Get-Date.  Nice addition.

  • Helpful Tip!!!

  • $culture = New-Object system.globalization.cultureinfo 'en-us'

    $date = Get-Date

    [System.DateTime]::Parse($date, $culture)

    PowerShell rocks!!!

  • Careful with that, as  date and culture is not fool proof:

    $culture = New-Object system.globalization.cultureinfo 'en-us'

    $date = Get-Date

    [System.DateTime]::Parse($date, $culture)

    Friday, 11 October, 2013 23:35:34

    get-date

    Sunday, 10 November, 2013 23:35:59

    -check the month & date being switch for a dutch locale v.s. a en-us one-

  • @Paul - that only happens to the Dutch for obvious reasons.

  • @jrv, although I think your remark is meant as a joke, but you may actually be on to something.  A lot of people in the Netherlands tend to simply use the OS in English (IT guys typically in US English). So culture info will be en-US.

    However, we do use European date notation, which is day-month-year rather than month/day/year.

    I've often run into problems with scripting (is VBscript as well as Powershell) because of this.

    p.s. not quite sure what the obvious reasons are?

  • brilliant