Thursday, May 24, 2012

Calculating the Years and Months Between Two Dates

I ran into an interesting problem that had a much shorter solution than I anticipated. I searched the web for simple solutions and ran across this post on msdn (http://forums.asp.net/t/1289294.aspx/1?TimeSpan+Years+and+Months). Suppose you have 2 dates and want to find the following information about the dates range:
  • Number of years
  • Number of months
  • Number of quarters
  • Number of half years
Often I will test algorithms in Powershell (or some scripting language) and then convert them in what whatever static language I need it to be in; this is one of those cases.
$d1 = [DateTime]::Parse("5/3/2022");
$d2 = [DateTime]::Parse("2/2/2012");
$d3 = [DateTime]::MinValue + ($d1 - $d2)
$d3.Year - 1 # 10
$d3.Month - 1 # 3
$d3.Day - 1 # 1
There are some assumptions that I am making in a couple calculations for my application. I only care about whole periods, so I will be using the floor function to select the correct count. I am also ignoring the days, they don't matter.
TimeSpan span = AmortSched.FirstPrincipalPymntDate - AmortSched.FirstPrincipaMatDate;
DateTime range = DateTime.MinValue + span;

int yearCount = range.Year - 1;
int monthCount = range.Month - 1;
int totalMonthCount = (yearCount * 12) + monthCount;
int totalQuarterCount = Math.Floor(totalMonthCount / 3);
int totalHalfYearsCount = Math.Floor(totalMonthCount / 6);

Thursday, May 3, 2012

Set Visual Studio 2010 Shortcuts Using Powershell

The awesome things you can do with the $dte object inside Visual Studio 2010 just keep piling up. I could not find any examples on how to do it with Powershell.

You can list the commands and their bindings with the following command. Important note... there are a LOT of commands and it will likely take several seconds to output everything.
$dte.Commands | ft -Property Name, Bindings

If you already know the command name, you can get the bindings using the following command.
$dte.Commands | ? { $_.Name -eq "View.TfsSourceControlExplorer" } | % {
    $_.Bindings;
}

Be careful to not choose a shortcut that is already in use. The following are some bindings that I find very useful. The first sets a convenient way to open the Source Control Explorer.
$dte.Commands | ? { $_.Name -eq "View.TfsSourceControlExplorer" } | % {
    $_.Bindings = "Global::Ctrl+W, Ctrl+1";
}

This opens the folder in Windows Explorer containing the current file.
$dte.Commands | ? { $_.Name -eq "File.OpenContainingFolder" } | % {
    $_.Bindings = "Global::Ctrl+Shift+Alt+O";
}

This opens the Attach to Process... dialog. I can't remember if this is the default shortcut, but here it is regardless.
$dte.Commands | ? { $_.Name -eq "Tools.AttachtoProcess" } | % {
    $_.Bindings = "Global::Ctrl+Alt+P";
}