0

我试图让一个人的年龄以年、月、日、小时、分钟和秒为单位。

这是我到目前为止所得到的(你可以说我是一个完全的 powershell 初学者):

$now = [datetime]::now
[datetime]$birthday = "12/22/2012 03:22:00"
$age = [datetime]$now - $birthday

Write-Host "My daughter's age is:" $age.Days "days" ($age.Hours) "hours" ($age.Minutes) "minutes" ($age.Milliseconds) "seconds"

输出是:

My daughter's age is: 59 days 10 hours 27 minutes 76 seconds

没关系,但是如果输出更“人类可读”会更棒:

1 Month 19 Days 10 hours 28 minutes 16 seconds

这实际上比我最初预期的要困难得多。代码必须知道每个月有多少天才能将天分成月和天。还要考虑到今年是闰年!

也许 PowerShell 可以在这里发挥一些魔力!

谢谢!

4

2 回答 2

0

我相信这就是你所追求的。

[datetime]$birthday = "12/22/2012 03:22:00"
$span = [datetime]::Now - $birthday
$age = New-Object DateTime -ArgumentList $Span.Ticks

Write-Host "My daughter's age is:" $($age.Year -1) Years $($age.Month -1) Months $age.Day "days" ($age.Hour) "hours" ($age.Minute) "minutes" ($age.second) "seconds"
于 2013-02-19T14:19:12.740 回答
0

请在生日后的第二天检查。还有1天!

正确的是:

[datetime]$birthday = "12/22/2012 03:22:00"
$span = [datetime]::Now - $birthday
$age = New-Object DateTime -ArgumentList $Span.Ticks

Write-Host "My daughter's age is:" $($age.Year-1) Years $($age.Month-1) Months ($age.Day-1) "days" ($age.Hour) "hours" ($age.Minute) "minutes" ($age.second) "seconds"
于 2016-04-12T12:30:44.243 回答