How to obtain the first day of a week

Start of a week is a specific datetime. Looking at this sentence, I can draw two points. The first one is that I need a class called StartOfTheWeek which denotes a subject in a proposition Start of a week is a specific datetime. The predicate, is a specific datetime, clearly tells me that this class should either implement some sort of DateTime interface or extend the same sort of abstract class. And you know what? There is one already, and it’s called an ISO8601DateTime.

Alright, no more philosophy, let’s just get right into it. Which weekday is the first day of the week? Since this datetime is in ISO8601 format, it dictates us that a week starts on Monday. It might differ depending on cultural traditions of course, but this standard is culture-agnostic, so it’s always Monday.

Here is how you can actually get the start of a week in code:

(new StartOfTheWeek(
    new FromISO8601('2020-04-23T01:28:04+07:00')
))
    ->value(); // returns 2020-04-20T00:00:00+07:00, which is Monday indeed

If you need to obtain the first day of the current week, just pass the current datetime:

(new StartOfTheWeek(
    new Now()
))
    ->value();

And if you want just a date of the beginning of the week, instead of a datetime, you can do the following:

(new FromISO8601DateTime(
    new StartOfTheWeek(
        new FromISO8601('2020-04-23T01:28:04+07:00')
    )
))
    ->value(); // returns '2017-04-20' string

Finally, in case you want to find the last day of the week, you can do simple math. Just get the first day, and then add six days to it:

(new Future(
    new StartOfTheWeek(
        new FromISO8601('2020-04-23T01:28:04+07:00')
    ),
    new NDays(6)
))
    ->value() // returns 2020-04-26T00:00:00+07:00

If you find that having a distinct class for getting the last day of a week would be more convenient, you can write it and create a pull request. If tests are in place and code is OK, I’ll merge it pretty soon.