简体   繁体   English

在Powershell中将一年中的日期值转换为日期

[英]Convert day of year value to date in Powershell

In Powershell, converting a date into a day of the year value is easy: 在Powershell中,将日期转换为一年中的某天很容易:

$DayOfYear = (Get-Date).DayofYear
Write-Host $DayOfYear
140

Is there a similar way to convert the day of year back into a date (ie 140 = 05/20/2013)? 有没有类似的方法可以将年份中的日期转换为日期(即140 = 05/20/2013)?

Try this: 尝试这个:

([datetime]"01/01/$((Get-Date).Year)").AddDays(140-1)

20. mai 2013 00:00:00

mai = may in norwegian :-) mai =五月挪威语:-)

您可以创建一个代表年初的DateTime对象,然后向其添加天数,例如:

(New-Object System.DateTime 2013,1,1).AddDays(140-1)

This might be helpful for you: 这可能对您有帮助:

$startdate_year = ([datetime]"01/01/$((Get-Date).Year)")
$a = (Get-Date $startdate_year).AddDays(139)
"Date: " + $a.ToShortDateString()

Now you will get the result like this: 现在您将获得如下结果:

Date: 5/20/2013

Use this method to avoid [datetime] objects and use Powershell syntax only: 使用此方法可以避免[datetime]对象,并且仅使用Powershell语法:

$DayOfYear = (Get-Date).DayOfYear
$Today = (Get-Date -Month 1 -Day 1).AddDays($DayOfYear-1)
"$($Today.ToString("MM/dd/yyyy")) is day $DayOfYear of 365"

Output: 输出:

10/03/2017 is day 276 of 365

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM