PowerShell今天的日期为4-15-2020(获取日期).AddMonths(-6).month)预计为4-15-2019,获得10/31/2020

时间:2020-04-15 12:23:19

标签: powershell date datetime

我正在使用PowerShell来获取前6个月的时间。使用foreach循环将今天的日期4-15-2020

$months = ((get-date).AddMonths(-1).month,(get-date).AddMonths(-2).month,(get-date).AddMonths(-3).month,(get-date).AddMonths(-4).month,(get-date).AddMonths(-5).month,(get-date).AddMonths(-6).month)
foreach($Month in $months){
$Year = (get-date).Year
$StartOfMonth = Get-Date -Year $Year -Month $Month -Day 1
$DaysInMonth = [DateTime]::DaysInMonth($Year, $Month)
$EndOfMonth = Get-Date -Year $Year -Month $Month -Day $DaysInMonth
$Month = $StartOfMonth.ToString("MMM/yyyy")
$StartOfMonth = $StartOfMonth.ToString("MM/dd/yyyy")
$EndOfMonth = $EndOfMonth.ToString("MM/dd/yyyy")
$StartOfMonth
$EndOfMonth
$Month
}

我得到:

03/01/2020
03/31/2020
Mar/2020
02/01/2020
02/29/2020
Feb/2020
01/01/2020
01/31/2020
Jan/2020
12/01/2020
12/31/2020
Dec/2020
11/01/2020
11/30/2020
Nov/2020
10/01/2020
10/31/2020
Oct/2020

和预期

03/01/2020
03/31/2020
Mar/2020
02/01/2020
02/29/2020
Feb/2020
01/01/2020
01/31/2020
Jan/2020
12/01/2019
12/31/2019
Dec/2019
11/01/2019
11/30/2019
Nov/2019
10/01/2019
10/31/2019
Oct/2019

这是错误还是我的代码有问题?

2 个答案:

答案 0 :(得分:3)

您继续根据当前年份设置年份-$Year = (get-date).Year

我将改为执行以下操作:

$today = Get-Date

foreach ($MonthOffset in -1..-6) {
    # Find a date in the intended month based on ([current date] + [month offset])
    # Extract year and month from that
    $MonthDate = $today.AddMonths($MonthOffset)
    $Year = $MonthDate.Year
    $Month = $MonthDate.Month

    $StartOfMonth = Get-Date -Year $Year -Month $Month -Day 1
    $DaysInMonth = [DateTime]::DaysInMonth($Year, $Month)
    $EndOfMonth = Get-Date -Year $Year -Month $Month -Day $DaysInMonth
    $Month = $StartOfMonth.ToString("MMM/yyyy")
    $StartOfMonth = $StartOfMonth.ToString("MM/dd/yyyy")
    $EndOfMonth = $EndOfMonth.ToString("MM/dd/yyyy")
    $StartOfMonth
    $EndOfMonth
    $Month
}

答案 1 :(得分:0)

感谢您的见解Mathias R. Jessen。我可以这样使用上面的代码:

foreach ($MonthOffset in -1..-6) {
    # Find a date in the intended month based on ([current date] + [month offset])
    # Extract year and month from that
    $today = Get-Date
    $MonthDate = $today.AddMonths($MonthOffset)
    $Year = $MonthDate.Year
    $Month = $MonthDate.Month

    $StartOfMonth = Get-Date -Year $Year -Month $Month -Day 1
    $DaysInMonth = [DateTime]::DaysInMonth($Year, $Month)
    $EndOfMonth = Get-Date -Year $Year -Month $Month -Day $DaysInMonth
    $Month = $StartOfMonth.ToString("MMM/yyyy")
    $StartOfMonth = $StartOfMonth.ToString("MM/dd/yyyy")
    $EndOfMonth = $EndOfMonth.ToString("MM/dd/yyyy")
    $StartOfMonth
    $EndOfMonth
    $Month
}