Monthly Archive

Categories

Just the date

Way back in this post https://richardspowershellblog.wordpress.com/2008/03/27/start-and-end-of-week/ I showed how to find the start of the week. I recently had a question about how to restrict the display to just the date.

 

PowerShell uses the .NET datetime class for working with dates so there will always be time information even if its set to 0. You can however restrict the display to just the date information

 

The ToShortDateString and ToLongDateString methods will give you just the date information but as a string

PS> $s = Get-Date -Hour 0 -Minute 0 -Second 0
PS> $d = $s.AddDays(-($s).DayOfWeek.value__)
PS> $d.ToShortDateString()
07/01/2018
PS> $d.ToLongDateString()
07 January 2018

 

Alternately you could create a custom format using the formatting strings found at

https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

For example

PS> Get-Date -Date $d -Format "yyyy-MM-dd gg"
2018-01-07 A.D.

 

You could combine the code lines to give

PS> $s = Get-Date -Hour 0 -Minute 0 -Second 0
PS> Get-Date -Date ($s.AddDays(-($s).DayOfWeek.Value__)) -Format "yyyy-MM-dd gg"
2018-01-07 A.D.

 

If you do this often enough then create a function

Comments are closed.