【问题标题】:Get Approximate Date from Week Number从周数获取大致日期
【发布时间】:2019-02-28 19:32:05
【问题描述】:

我正在从 WMI 获取有关监视器的信息。有称为“WeekOfManufacture”和“YearOfManufacture”的属性。在这种情况下是:

周:24 年份 : 2009

我正在尝试获取与此相对应的大致日期。

我这样做是为了得到一个非常粗略的估计:

(Get-Date -Date $YearOfManufacture/01/01).AddDays(7*$WeekOfManufacture)

但显然“周”不一定总是有 7 天。

最好的方法是什么?

我现在使用的完整代码是:

$Monitors = Get-WmiObject WmiMonitorID -Namespace root\wmi

foreach ($Monitor in $Monitors) {
    $Manufacturer = ($Monitor.ManufacturerName -notmatch 0 | ForEach{[char]$_}) -join ""
    $Code = ($Monitor.ProductCodeID -notmatch 0 | ForEach{[char]$_}) -join ""
    $Name = ($Monitor.UserFriendlyName -notmatch 0 | ForEach{[char]$_}) -join ""
    $Serial = ($Monitor.SerialNumberID -notmatch 0 | ForEach{[char]$_}) -join ""

    $WeekOfManufacture = $Monitor.WeekOfManufacture
    $YearOfManufacture = $Monitor.YearOfManufacture

    $DateManufacture = (get-date -Date $YearOfManufacture/01/01).AddDays(7*$WeekOfManufacture)

    "$Manufacturer - $Code - $Name - $Serial - $DateManufacture" 
}

返回类似(信息混淆):

SAM - 1234 - SycMastr - XXXX - 06/18/2009 00:00:00 SAM - 1234 - SycMastr - XXXX - 09/10/2009 00:00:00

【问题讨论】:

  • 您可以使用 .DayOfWeek 属性。前任。 $DateManufacture = (get-date -Date $YearOfManufacture/01/01).DayOfWeek 确定是否是工作日和/或其他属性
  • 十年±7天?谁在乎?

标签: powershell date week-number


【解决方案1】:

来自 Technet 的回答完美无缺 (https://social.technet.microsoft.com/Forums/en-US/f65c80b0-f74f-4234-870c-c5ffe8d9b1ea/powershell-get-date-from-week-number-of-year?forum=ITCG) :

Function FirstDateOfWeek
{
    param([int]$year, [int]$weekOfYear)

    $jan1 = [DateTime]"$year-01-01"
    $daysOffset = ([DayOfWeek]::Thursday - $jan1.DayOfWeek)

    $firstThursday = $jan1.AddDays($daysOffset)
    $calendar = ([CultureInfo]::CurrentCulture).Calendar;

    $firstWeek = $calendar.GetWeekOfYear($firstThursday, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [DayOfWeek]::Monday)

    $weekNum = $weekOfYear

    if($firstweek -le 1) { $weekNum -= 1 }

    $result = $firstThursday.AddDays($weekNum * 7)
    return $result.AddDays(-3)    
}

FirstDateOfWeek -year 2009 -weekOfYear 24

8 juin 2009 00:00:00

【讨论】:

  • 耐人​​寻味;该代码是此 C# 答案的 PowerShell 端口:stackoverflow.com/a/9064954/45375,其中提到使用星期四作为与 ISO 8601 相关的参考点。
猜你喜欢
  • 1970-01-01
  • 2010-11-19
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多