Reputation: 27
i wrote the below code to get the last week start and end considering monday as start day
$date_2 = ((Get-Date).adddays(-(6+(Get-Date -UFormat %u)))).date
Write-Host "From : $date_2"
$date_3 = $date_2.AddDays(6)
Write-Host "To : $date_3"
It is working fine.
O/P
From : 10/07/2019 00:00:00
To : 10/13/2019 00:00:00
Now need to get the start day of the week considering monday as start day. e.g. today is 15th Oct Tuesday so it should give
From : 10/14/2019 00:00:00
To : 10/15/2019 00:00:00
e.g. if it is 18th Oct then it should be
From : 10/14/2019 00:00:00
To : 10/18/2019 00:00:00
Need your help on this.
Upvotes: 1
Views: 4993
Reputation: 588
This should be what you're looking for (with the total days in the month as an added bonus).
# Get the current day
$date = Get-Date;
# determine the day, month, and year
$curDay = $date.DayOfWeek;
$curMonth = $date.Month;
$curYear = $date.Year;
# get total days in month
$totalDaysInMonth = [DateTime]::DaysInMonth($curYear, $curMonth);
switch($curDay){
"Monday" {
# this is where we want to be
$offset = 0;
}
"Tuesday"{
$offset = -1;
}
"Wednesday"{
$offset = -2;
}
"Thursday"{
$offset = -3;
}
"Friday"{
$offset = -4;
}
"Saturday"{
$offset = -5;
}
"Sunday"{
$offset = -6;
}
}
# Lets determine the start of the week
$startOfWeek = $date.AddDays($offset);
$endOfWeek = $startOfWeek.AddDays(6);
# lets show our findings
Write-Host "From: $startOfWeek";
Write-Host "To: $endOfWeek";
Upvotes: -1
Reputation: 7479
this uses the builtin [DayOfWeek]
enum. [grin]
$Today = (Get-Date).Date
$Monday = $Today.AddDays(1 - $Today.DayOfWeek.value__)
$Sunday = $Monday.AddDays(6)
'Week starts {0}' -f $Monday
'Week ends {0}' -f $Sunday
output ...
Week starts 2019-10-14 12:00:00 AM
Week ends 2019-10-20 12:00:00 AM
Upvotes: 4
Reputation: 2208
You could use the following function which accepts the current date as input.
Based on that date and the day of the week as an INT it will substract one day until it's monday.
function Get-WeekStartDate
{
param
(
[System.DateTime]$Date
)
while ((Get-Date -Date $Date).DayOfWeek.value__ -ne 1)
{
$Date = $Date.AddDays(-1)
}
return $Date
}
Get-WeekStartDate -Date (Get-Date)
Upvotes: 2
Reputation: 5227
$monday = (Get-Date -Hour 0 -Minute 0 -Second 0).AddDays(-(Get-Date).DayOfWeek.value__ + 1)
Based on my checking, the value of (Get-Date).DayOfWeek.value__
(numeric value of DayofWeek
property - source) is 0
for Sunday, 1
for Monday and so on. So you subtract n
days from today 00:00:00. You can do this using .AddDays(-n)
.
You'd receive Sunday as a result so you add 1, to get Monday.
I tested it on two machines where I have Monday and Sunday set as first day of week (can be checked by [System.Globalization.DateTimeFormatInfo]::CurrentInfo.FirstDayOfWeek
) and in both cases it works the same.
Upvotes: 0