0

I have the below code which gets the earliest date from a selection of date in the format of yyyy-mm-dd, alongside a message. I need to use the date that's been returned to populate my message by way of a declare statement using If and Else I think. For my first yyyy value if the month is less than 8 (August), then I need to use yyyy-1 from my original above mentioned selection, and if its a month greater than 8 (August), then I need to use the returned yyyy from my original selection. I then need this first value to then have / followed by a 2nd year returned, which will be plus 1 year to the first yyyy value. I am using Powershell, so something in .net would be really handy.

ReturnedResults

$dt = New-Object System.Data.DataTable;
$dt.Columns.Add("LearnStartDate");
$dt.Columns.Add("Message");

$dr = $DS.Tables["LearningDelivery"].Select("LearnStartDate =  
min(LearnStartDate)")[0];


Write-Output $dt.Rows.Count;

$dt.Rows.Add($dr["LearnStartDate"].Substring(0,10),"Our message");
  • The return value from this code is attached in screenshot –  Aug 07 '18 at 13:08
  • 1
    Never saw a question with that bunch of words hiding what you are really after. If you get a month as an integer there is no year in there. IMO it would be easiest if you tell something about `$DS` where data originates from. –  Aug 07 '18 at 13:18
  • $ds is a dataset that's been created as a new object, and has been filled with data from an xml file, which includes these dates. –  Aug 07 '18 at 13:21

1 Answers1

3

PowerShell can actually convert your string date to a date object automatically by using the [datetime] accelerator:

[datetime]$LearnStartDate = $dr["LearnStartDate"]

The Datetime object returned to $LearnStartDate then has various properties, including a .Month property that we can use to interrogate what the month value is, and a .AddYears method that we can use to add 1 to the year:

if ($LearnStartDate.Month -lt 8) { 
    $FirstYear = $LearnStartDate.AddYears(1).Year 
} 
Else { 
    $FirstYear = $LearnStartDate.Year 
}

$SecondYear = $FirstYear + 1

"FirstYear: $FirstYear"
"SecondYear: $SecondYear"

Beware that using [DateTime] will be using the localisation settings of you local machine, so you might get different results where this varies.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • That's amazing. Thank you!! –  Aug 07 '18 at 13:57
  • 1
    Good advice re properties and methods of `[datetime]`, but casting to `[datetime]` in PowerShell always uses the _invariant_ culture, not the _current_ one - see https://stackoverflow.com/a/37603732/45375 – mklement0 Aug 08 '18 at 03:40