I will give a solution that makes use of the library date-fns. The use of this medium reduces the work we would have writing all the logic in hand, as the code becomes more simplified and easy to understand.
If it is not possible to use third-party libraries for your solution, just ignore my answer.
Come on, knowing we can get the current date, or a future date, using Date
, you can import the date-fns
via Cdn:
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js">
</script>
After importing via Cdn, we can use dateFns
in the code.
Within this, we have the methods:
startOfWeek
: which returns the start date of the week
endOfWeek
: which returns the end date of the week
Both methods receive the object instance Date
, and resume the figures reported above.
Let’s take the example:
let date = new Date();
const inicioSemana = dateFns
.startOfWeek(date, { weekStartsOn: 0 })
.toLocaleDateString('pt');
const fimSemana = dateFns
.endOfWeek(date, { weekStartsOn: 0 })
.toLocaleDateString('pt');
console.log('Para a data: ', date.toLocaleDateString('pt'));
console.log('Inicio da semanda: ', inicioSemana);
console.log('Fim da semanda: ', fimSemana);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>
Notice that:
- placed
toLocaleDateString('pt')
to format the date to the standard you entered.
- has that object
{ weekStartsOn: 0 }
where the value 0
represents the beginning of the week, in this case, Sunday. If you change to 1
, the beginning of the week will be Monday.
The code really works?
Let’s test for a future date, December 29th:
let date = new Date();
date.setDate(29) // dia 29 de dezembro
const inicioSemana = dateFns
.startOfWeek(date, { weekStartsOn: 0 })
.toLocaleDateString('pt');
const fimSemana = dateFns
.endOfWeek(date, { weekStartsOn: 0 })
.toLocaleDateString('pt');
console.log('Para a data: ', date.toLocaleDateString('pt'));
console.log('Inicio da semanda: ', inicioSemana);
console.log('Fim da semanda: ', fimSemana);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>
Now let’s refatora to adapt to your code:
let date = new Date();
function primeiroDiaSemanaData(date) {
const inicioSemana = dateFns
.startOfWeek(date, { weekStartsOn: 0 })
.toLocaleDateString('pt');
return inicioSemana;
}
function ultimoDiaSemanaData(date) {
const fimSemana = dateFns
.endOfWeek(date, { weekStartsOn: 0 })
.toLocaleDateString('pt');
return fimSemana;
}
console.log('Para a data: ', date.toLocaleDateString('pt'));
console.log('Inicio da semanda: ', primeiroDiaSemanaData(date));
console.log('Fim da semanda: ', ultimoDiaSemanaData(date));
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>
It has to be a manual solution like Voce is doing or you accept use of some library to help answer?
– Cmte Cardeal