How can I get the DateTime for the start of the week?
Use an extension method. They're the answer to everything, you know! ;)
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
}
Which can be used as follows:
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
Get the date of the start week of a given date c#
I would do something like this:
Parse the date from string to DateTime object (if required)
Add days current day of the week * -1 (turn it negative) + 1
string s = "2018-08-23 13:26";
DateTime dt = DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
DateTime startOfWeek = dt.AddDays(((int)(dt.DayOfWeek) * -1) + 1);
Console.WriteLine(startOfWeek);
Here's a Fiddle
Edit: If you are bothered about the sunday going to the next Monday,
then change the Sunday to remove 7 days from the current date like so;
string s = "2018-08-17 13:26";
DateTime dt = DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
bool isSunday = dt.DayOfWeek == 0;
var dayOfweek = isSunday == false ? (int)dt.DayOfWeek : 7;
DateTime startOfWeek = dt.AddDays(((int)(dayOfweek) * -1) + 1);
Console.WriteLine(startOfWeek);
How to get start of or end of week in dart
You can get the weekday from the DateTime using https://api.dart.dev/stable/2.5.1/dart-core/DateTime/weekday.html and add/subtract this number from you date:
void main() {
final date = DateTime.parse('2019-10-08 15:43:03.887');
print('Date: $date');
print('Start of week: ${getDate(date.subtract(Duration(days: date.weekday - 1)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - date.weekday)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
UPDATE
Please read and upvote the answer from lrn. He knows a lot more about this stuff than me. :)
How to set start of the week as Sunday and end as Saturday in Dart?
Since DateTime.weekday
counts from 1 (Monday) to 7 (Sunday):
date.subtract(Duration(days: date.weekday - 1))
will give us the date of the start of the week using what DateTime
considers to be the first day of the week (Monday). To treat Sunday as the first day of the week instead, we can try to get the previous day from that:
date.subtract(Duration(days: date.weekday - 1)).subtract(const Duration(days: 1))
The above is algebraically equivalent to date - (weekday - 1) - 1
, which can be simplified to just date - weekday
. But that's not quite right because weekday
ranges from [1, 7], and we never want to subtract 7 days. In that case, we want to subtract 0. The modulus operator handles that nicely, ultimately giving us:
DateTime findFirstDateOfTheWeek(DateTime date) {
return date.subtract(Duration(days: date.weekday % DateTime.daysPerWeek));
}
To get the last day of the week where Saturday is treated as the last day of the week, you can just get the first day of the week and add 6 days:
DateTime findLastDateOfTheWeek(DateTime date) {
return findFirstDateOfTheWeek(date).add(
const Duration(days: DateTime.daysPerWeek - 1));
}
Get date of first Monday of the week?
This is what i use (probably not internationalised):
DateTime input = //...
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime monday = input.AddDays(delta);
get the start and end timestamp of the current week in python
You can use datetime.replace()
:
from datetime import date, datetime, timedelta
today = datetime.now() # or .today()
start = (today - timedelta(days=today.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
end = (start + timedelta(days=4)).replace(hour=23, minute=59, second=0, microsecond=0)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
output
Today: 2021-07-08 22:56:19.277242
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00
Dart/Flutter get first DateTime of this week
If Sunday is your first day of week.
var d = DateTime.now();
var weekDay = d.weekday;
var firstDayOfWeek = d.subtract(Duration(days: weekDay));
According to Flutter docs weekDay
returns
The day of the week [monday]..[sunday].
- In accordance with ISO 8601
- a week starts with Monday, which has the value 1.
if Monday is first day of week then
var firstDayOfWeek = d.subtract(Duration(days: weekDay - 1));
A simpler way of finding the start of the week for any start day
The number of days between START_DAY
and now
is now.weekday() - START_DAY
. However, if today is before START_DAY
(e.g. if today is Wednesday and START_DATE
is 6 = Sunday), that number will be negative, and subtracting it from today would give you a date in the future.
Since you probably don't want that, you need the difference modulo 7:
week_start = now.date() - timedelta(days=(now.weekday() - START_DAY) % 7)
Examples:
>>> from datetime import datetime, timedelta
>>> now = datetime(2017, 2, 1)
>>> print(now.strftime("%d/%m/%y (%a)"))
01/02/17 (Wed)
>>> for START_DAY in range(7):
... start_week = now.date() - timedelta(days=(now.weekday() - START_DAY) % 7)
... print(start_week.strftime("%d/%m/%y (%a)"))
...
30/01/17 (Mon)
31/01/17 (Tue)
01/02/17 (Wed)
26/01/17 (Thu)
27/01/17 (Fri)
28/01/17 (Sat)
29/01/17 (Sun)
Related Topics
When to Use .First and When to Use .Firstordefault With Linq
Is It Better to Return Null or Empty Collection
SQL Data Reader - Handling Null Column Values
Do You Need to Dispose of Objects and Set Them to Null
Getting Multiple Keys of Specified Value of a Generic Dictionary
Deserialize Json to C# Classes
Which Parsers Are Available For Parsing C# Code
What's the Main Difference Between Int.Parse() and Convert.Toint32
Make a Borderless Form Movable
How to Create Json String in C#
Best Timer For Using in a Windows Service
Is There a Good Linq Way to Do a Cartesian Product