rsc*_*rin 5 powershell date getdate
我每个月的第4天和第14天安排一个脚本.
当脚本在4号开始时,我需要获取上个月的最后一天(简单,$ a.AddDays(-5))
当脚本在14日开始时,我需要获得2个月前的最后一天.
例如:
14 april.
I want to get:28 february 2013
Run Code Online (Sandbox Code Playgroud)
这怎么可能?我也希望以格式yyyymmdd获取日期
UDPDATE:
您的解决方案是否可能无法适应当年的变化?
如果我在1月,$(获取日期).month -1结果0.所以我这样做:
$datenow = Get-date
if $datenow.day -eq 14
$datenow.AddDays(-14)
Run Code Online (Sandbox Code Playgroud)
然后我计算
$LastDayInMonth = [System.DateTime]::DaysInMonth($(Get-date).Year, $(Get-date.Month))
$datenow.AddDays(-$LastDayInMonth)
$datestring = $datenow.ToString("yyyyMMdd")
Run Code Online (Sandbox Code Playgroud)
要在字符串中获取日期:
$(get-date).Date.ToString("yyyyMMdd")
Run Code Online (Sandbox Code Playgroud)
为了获得前两个月的最后一天:
if($(get-date).Day -eq 14){
$LastDayInMonth = [System.DateTime]::DaysInMonth($(get-date).Year, $($(get-date).Month - 2))
}
Run Code Online (Sandbox Code Playgroud)
更新
这条线
$LastDayInMonth = [System.DateTime]::DaysInMonth($(get-date).Year, $($(get-date).Month - 2))
Run Code Online (Sandbox Code Playgroud)
使用DaysInMonthSystem.DateTime类中的静态方法获取传递给它的月份中的日期.它的文档就在这里.它将两个参数作为输入,月份作为整数,年份也作为整数.
在我们的例子中,我们想要在本月前2个月,所以我们传入的月份参数
$(get-date).month - 2
Run Code Online (Sandbox Code Playgroud)
然后用括号括起来确保powershell进行计算,然后传递计算结果.get-date是一个powershell cmdlet,它将当前日期和时间作为.NET dateTime对象提供,因此我们可以使用所有属性和方法.
整体
[System.DateTime]::DaysInMonth()
Run Code Online (Sandbox Code Playgroud)
只是在PowerShell中调用静态方法的方法.
更新2
一旦你获得了该月的最后一天,你可以通过以下方式连接字符串:
$LastDayInMonthString = "$($(get-date).AddMonths(-2).ToString("yyyyMM"))$LastDayInMonth"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8152 次 |
| 最近记录: |