2008 Scripting Games - Solution for Beginner’s Event 5
29
Feb
This continues my series of solution posts for the 2008 Scripting Games with my solution for the Beginner Event 5 which was a simple test of your ability to accept command-line parameters and play with dates.
The only real trick was that you were required to calculate the number of months and days two different ways: total days and calendar months, and then complete months with days remainder. There are lots of ways to do this, but one of the simplest things is to use the VB.net DateAndTime function DateDiff:
# use JOIN so that the argument doesn't have to be quoted
# ie: you can call: .\Beginner5.ps1 January 5, 2008
# and the join here would wrap the 4 resulting args into a single string
# and then cast that to a date ...
[DateTime]$date = [string]::join(" ",$args)
# think of this as adding a reference (the $null just throws out the result text)
$null = [Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
# think of this as a C# using statement
$iv = [Microsoft.VisualBasic.DateInterval]
$days = [Microsoft.VisualBasic.DateAndTime]::DateDiff( $iv::Day, [DateTime]::Now, $date)
$months = [Microsoft.VisualBasic.DateAndTime]::DateDiff( $iv::Month, [DateTime]::Now, $date)
"Days: $days"
"Months: $months"
if( $date.Day -gt [DateTime]::Now.Day ) {
$days = $date.Day - [DateTime]::Now.Day
} else {
$months--
$days = ($date - [DateTime]::Now.AddMonths($months)).Days
}
"Months/Days: {0} / {1}" -f $months, $days
You see, there’s nothing really worth talking about in that, other than the fact that it’s using that DateDiff, and the way I used join on the $args array to let you pass dates like “January 5, 2008” without the quotes.
- By Joel 'Jaykul' Bennett
- Tagged as: