Radagast
Radagast

Reputation: 1096

Get the number of Days in the current month using powershell

I have the need to retrieve the number of days in the current month, and despite my research, I have yet to find anything in powershell that does it. The following is what I have currently built to get the result I want. is there a better way to do it?

Please note that I am limited to Powershell

    #check to see if this is a leap year
    function LYC
    {
        if ([System.DateTime]::isleapyear((Get-Date).Year))
        {
            $Global:LY = True
        }
    }
    #Get the number of days in current month
    function fNOD
    {
        $MNum = (Get-Date).Month
        switch ($MNum)
        {
            1   {$Global:DaysInMonth=31}
            2   {
                    LYC
                    if (LY)
                    {
                        $Global:DaysInMonth=29
                    } else {
                        $Global:DaysInMonth=28
                    }
                }
            3   {$Global:DaysInMonth=31}
            4   {$Global:DaysInMonth=30}
            5   {$Global:DaysInMonth=31}
            6   {$Global:DaysInMonth=30}
            7   {$Global:DaysInMonth=31}
            8   {$Global:DaysInMonth=31}
            9   {$Global:DaysInMonth=30}
            10  {$Global:DaysInMonth=31}
            11  {$Global:DaysInMonth=30}
            12  {$Global:DaysInMonth=31}
        }
    }

Upvotes: 3

Views: 12697

Answers (3)

Mr Q
Mr Q

Reputation: 11

Assuming you want it for any date stored in $date:

((get-date $date -Day 1 -hour 0 -Minute 0 -Second 0).AddMonths(1).AddSeconds(-1)).Day

Upvotes: 1

Austin T French
Austin T French

Reputation: 5131

This seems to me like it might be deceptively easy:

$numDays = ((Get-Date -Month 3) - (Get-Date -Month 2))

28 days in February, July minus June gives me 30 days.

As mentioned below, that apparently sometimes does some weird integer rounding that gives off 29d, 23h, 59m or something else not right.

This seems to be consistent:

$monthLess = Get-Date -Month 4
$NumDays = (Get-Date -Month 5).Subtract($monthLess)

Upvotes: 0

Andy Arismendi
Andy Arismendi

Reputation: 52567

http://msdn.microsoft.com/en-us/library/system.datetime.daysinmonth.aspx

# static int DaysInMonth(int year, int month)
[DateTime]::DaysInMonth(2013, 3)

Upvotes: 15

Related Questions