6

If i provide the week#, how might i go about getting the first day (and month) and the last day (and month) of that particular week?

This week for instance would be April 26 and May 2

I know in PHP i can do the first and last day of the week like so:

$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));

But i'm not sure how to translate that to twig and of course also include the month.

2 Answers 2

9

That code in Twig would be:

{% set day = now|date('w') %}
{% set weekStart = now|date_modify("-#{day} days")|date('m-d-Y') %}
{% set weekEnd = now|date_modify("+#{6-day} days")|date('m-d-Y') %}
2
  • I noticed that there's a difference between now and 'now', Brandon. now not returning the date calculated to be in the right timezone?
    – carlcs
    May 13, 2015 at 11:21
  • @carlcs We fixed that in Craft 2.4.2670 :) Jun 24, 2015 at 16:12
5

The version below could be more understandable in some cases.

First day of week (assuming Monday is the first day):

{{ now | date_modify('monday this week') | date('m-d-Y') }}

or alternatively:

{{ now | date_modify('this week') | date('m-d-Y') }}

Last day of week (assuming Sunday is the last day):

{{ now | date_modify('sunday this week') | date('m-d-Y') }}

First day of month:

{{ now | date_modify('first day of this month') | date('m-d-Y') }}

Last day of month:

{{ now | date_modify('last day of this month') | date('m-d-Y') }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.