上一季度、上一季度和上一年- PowerShell函数

roejwanj  于 2023-01-30  发布在  Shell
关注(0)|答案(1)|浏览(118)

我在下面跑
@上一季度-选择日期添加(dd,-1,日期添加(qq,日期差异(qq,0,获取日期()),0)),23 -返回2021-12-31 00:00:00.000 @上一季度-选择日期添加(qq,-1,日期添加(dd,-1,日期添加(qq,日期差异(qq,0,获取日期()),0))),23 -返回2022-12-31 00:00:00.000 @上一年度-选择日期添加(yy,-1,日期添加(dd,-1,日期添加(qq,日期差异(qq,0,获取日期()),0)),23;- 返回日期2022年9月30日00:00:00.000
我该如何在Powershell中编写这些代码才能获得上面的内容?
它有什么我可以使用的功能吗?我看过get-date,但似乎在PowerShell中获得上面的功能并不那么简单
希望在PS中建立逻辑方面得到一些帮助

7nbnzgx9

7nbnzgx91#

这里有一些表达式,给予了你想要的值。我没有对它们进行广泛的测试,所以你可能想写一些Pester测试或其他东西来验证它们的边缘情况,等等...
它还假设您不关心时间部分-如果这很重要,您可能需要在$quarterStart表达式中清除它...

$timestamp = [datetime] "2022-01-12";
write-host "timestamp = $timestamp";
# timestamp = 01/12/2022 00:00:00

# find the start of the *current* quarter - it's easier and
# clearer to work out the others from this interim value
$quarterStart = $timestamp.AddDays(-$timestamp.Day + 1).AddMonths(-($timestamp.Month-1) % 3);
write-host "quarter start = $quarterStart";
# quarter start = 01/01/2022 00:00:00

# end of the quarter before the current one
# (i.e. one day before the current quarter start)
$lastQuarter = $quarterStart.AddDays(-1);
write-host "last quarter = $lastQuarter";
# last quarter = 12/31/2021 00:00:00

# end of the quarter before the last one
# (i.e. three months and one day before the current quarter start)
$previousQuarter = $quarterStart.AddMonths(-3).AddDays(-1);
write-host "previous quarter = $previousQuarter";
# previous quarter = 09/30/2021 00:00:00

# end of the previous year
# (i.e. 31st December of the previous year)
$lastYear = new-object DateTime(($timestamp.Year - 1), 12, 31);
write-host "last year = $lastYear";
# last year = 12/31/2021 00:00:00

相关问题