Get the last day of a month on powershell

Much simpler solution is to call into the DaysInMonth function

[DateTime]::DaysInMonth(2018, 11)

For the current month that would look like:

$today = get-date
$lastDay = [DateTime]::DaysInMonth($today.Year, $today.Month)
$firstDate = [DateTime]::new($today.Year, $today.Month, 1)
$lastDate  = [DateTime]::new($today.Year, $today.Month, $lastDay)

$firstDate
$lastDate

This also works around any hindering daylight savings changes and other weird things that can happen with timezones etc.

Or if pure strings are all you need:

(get-date -Format "yyyy/MM") + "/1"
(get-date -Format "yyyy/MM") + "/" + [DateTime]::DaysInMonth((get-date).Year, (get-date).Month)

An easy way is to take the last day of the previous year and add 1..12 months to it:

1..12 | % { (New-Object DateTime(2017,12,31)).AddMonths($_) }

Output will be in the user's date/time format, in my case Dutch:

woensdag 31 januari 2018 00:00:00
woensdag 28 februari 2018 00:00:00
zaterdag 31 maart 2018 00:00:00
maandag 30 april 2018 00:00:00
donderdag 31 mei 2018 00:00:00
zaterdag 30 juni 2018 00:00:00
dinsdag 31 juli 2018 00:00:00
vrijdag 31 augustus 2018 00:00:00
zondag 30 september 2018 00:00:00
woensdag 31 oktober 2018 00:00:00
vrijdag 30 november 2018 00:00:00
maandag 31 december 2018 00:00:00

If required you can format it as you need it, e.g.

1..12 | % { (New-Object DateTime(2017,12,31)).AddMonths($_).ToString("yyyyMMdd") }

20180131
20180228
20180331
20180430
20180531
20180630
20180731
20180831
20180930
20181031
20181130
20181231

This seems simple enough

$firstDate = [DateTime]::new($reportDate.Year, $reportDate.Month, 1)
$lastDate=$firstDate.AddMonths(1).AddDays(-1)

Tags:

Powershell