get previous month name.lower() not number

I am trying to get the previous month name, not the number, currently the line below gives me the previous month as a number but I need it as the name and in lowercase.

(get-date).Month-1;

Thank you!

edit: Got my answer, thank you guys!

Posted Dec 5, 2017, 5:56 PM UTC · edited

911
Ta11ow•
(Get-Culture).DateTimeFormat.GetMonthName((Get-Date).AddMonths(-1).Month).ToLower()

Or alternatively, using your existing code:

(Get-Culture).DateTimeFormat.GetMonthName((Get-Date).Month-1).ToLower()

EDIT: You can alternatively use this:

[System.Globalization.DateTimeFormatInfo]::CurrentInfo.GetMonthName((Get-Date).Month-1)

EDIT 2: There is also this method:

[CultureInfo]::CurrentCulture.DateTimeFormat.GetMonthName((Get-Date).Month-1)

Seems like there isn't a short way to do it, unfortunately. If I were planning on calling this more than once I'd do something like this...

$DTformat = (Get-Culture).DateTimeFormat
$monthname = $DTformat.GetMonthName((Get-Date).Month-1).ToLower()
9
fakefadingOP•

Thank you! I'll use the first line :)

2
jollyfreek•
(get-date((get-date).addmonths(-1)) -format MMMM).ToLower()
6
neogohan•

Put more simply:

(Get-Date).AddMonths(-1).ToString("MMMM").ToLower()

ToString allows you to specify the format, so no need for duplicate "Get-Date" commands.

Edit: Just saw u/Qel_Hoth's reply here with the same code. He notes the speed improvement as well.

4
jollyfreek•

I have a few places I can use this. Thanks!

4
ESKIMO_dk•

What about this?

$a = new-object system.globalization.datetimeformatinfo
$b = $a.MonthNames
$b[(get-date).Month-2].ToLower()
4
fakefadingOP•

thanks!

1
mirrax•

You could get the previous month, then use another Get-Date with the -Format MMMM parameter to get the month as a string and then convert to lowercase.

(Get-Date -Date (Get-Date).AddMonths(-1) -Format MMMM).ToLower()
3
Ta11ow•

This is definitely a much cleaner method than what I turned up, I like it!

2
Qel_Hoth•

Alternatively you can also do

(Get-Date).AddMonths(-1).ToString("MMMM").ToLower()

Get-Date can be substituted with a datetime object if you have one. This should be considerably faster if it's part of a script that's running many times.

Running a Measure-Command on mine came back with 0.2983ms. The one u/mirrax posted is 2.5292ms.

6
omrsafetyo•

The -uformat parameter helps with stuff like this.

(Get-Date ([DateTime]::Now.AddMonths(-1)) -uformat %B).ToLower()

(Get-Date (Get-Date).AddMonths(-1) -uformat %B).ToLower()
2