Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell get-date in 1st,2nd,2rd,4th Formats

Tags:

powershell

I am trying to format a date in PowerShell as DayOfWeek Month Day(st|nd|rd|th) year format.

(Get-Date).AddDays(+1).ToString('D')

The output is "Tuesday, July 05, 2016" but need it in this format: Tuesday July 5th 2016

if date(Get-Date) % 100 IN (11, 12, 13) THEN 'th'
    if (Get-Date) % 10 = 1 THEN 'st'
    if (Get-Date) % 10 = 2 THEN 'nd'
    if (Get-Date) % 10 = 3 THEN 'rd'
like image 584
DisplayName Avatar asked Feb 07 '23 15:02

DisplayName


1 Answers

One possible solution could look like this

function Get-DateOrdinalSuffix([datetime]$Date) {
    switch -regex ($Date.Day.ToString()) {
        '1(1|2|3)$' { 'th'; break }
        '.?1$'      { 'st'; break }
        '.?2$'      { 'nd'; break }
        '.?3$'      { 'rd'; break }
        default     { 'th'; break }
    }
}

$d = (Get-Date).AddDays(1)
$suffix = Get-DateOrdinalSuffix $d
$dateFormatted = "{0} {1:MMMM} {2}{3} {4}" -f $d.DayOfWeek, $d, $d.Day, $suffix, $d.Year
like image 177
DAXaholic Avatar answered Feb 12 '23 06:02

DAXaholic