PowerShell中日期时间的星期几比较逻辑 [英] Date Time day of the week comparison logic in PowerShell

查看:280
本文介绍了PowerShell中日期时间的星期几比较逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

日期时间对象使我们可以执行以下操作:

Date Time objects allow us to perform actions like this:

$CurrentDate = Get-Date
$TextDate = get-date -date "02/10/2016"

if ($TextDate -lt $CurrentDate){
    Write-Host "True"
}
else {
    Write-Host "False"
}

这将输出 True 是因为$ TextDate小于$ CurrentDate。

This outputs "True" because $TextDate is less than $CurrentDate.

按照相同的逻辑,为什么以下代码输出为false?

Following the same logic, why does the following code output false?

$CurrentDate = Get-Date -UFormat %V
$TextDate = Get-Date -date "02/10/2016"
$TextDate = Get-Date -date $TextDate -UFormat %V

if ($TextDate -lt $CurrentDate){
    Write-Host "True"
}
else {
    Write-Host "False"
}

唯一的区别是我们正在比较一年中的星期。如果将比较更改为 -gt ,代码将返回True。

The only difference is that we are comparing the week of the year. If you change the comparison to -gt, the code returns True.

推荐答案

带格式的日期是字符串,而不是整数。字符串 6 在字符串 11 之后。

Formatted dates are strings, not integers. The string "6" is after the string "11".

这将是最正确的方法:

首先,确定一年的第一周的实际含义是:

First, decide what the "first week of the year" actually means:

$CalendarWeekRule = [System.Globalization.CalendarWeekRule]::FirstDay;
#$CalendarWeekRule = [System.Globalization.CalendarWeekRule]::FirstFourDayWeek;
#$CalendarWeekRule = [System.Globalization.CalendarWeekRule]::FirstFullWeek;

然后,确定一周中的哪一天是一周的第一天:

Then, decide which day of the week is the first day of the week:

$FirstDayOfWeek = [System.DayOfWeek]::Sunday;
#$FirstDayOfWeek = [System.DayOfWeek]::Monday;
#Any day is available

然后您可以获得正确的星期数:

Then you can get your correct week number:

$Today = (Get-Date).Date;
$TodayWeek = [cultureinfo]::InvariantCulture.Calendar.GetWeekOfYear($Today, $CalendarWeekRule, $FirstDayOfWeek);

$TargetDate = Get-Date -Date "2016-02-10";
$TargetWeek = [cultureinfo]::InvariantCulture.Calendar.GetWeekOfYear($TargetDate, $CalendarWeekRule, $FirstDayOfWeek);

if ($TargetWeek -lt $TodayWeek) { $true } else { $false }

请注意,如果要整周使用ISO 8601,则为稍微复杂些

Note that if you want a full ISO 8601 week, it's somewhat more complicated.

这篇关于PowerShell中日期时间的星期几比较逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆