How to get the date of the first and last days of the current week with Javascript?

Asked

Viewed 389 times

0

I need to get the date of the first and last days of the current week. For example, we are in Christmas week, and I would like the function primeiroDiaSemanaData() return 20/12/2020 and the function ultimoDiaSemanaData() return 26/12/2020.

I can’t do it. Someone knows how to help me?

inserir a descrição da imagem aqui

function primeiroDiaSemanaData() {
    var date = new Date();
    var today = date.getDate();
    var dayOfTheWeek = date.getDay();
    var newDate = date.setDate(today - dayOfTheWeek + 7);

    var dataInicial = new Date(newDate);

    return dataInicial;
}

function ultimoDiaSemanaData() {
    var date = new Date();
    var today = date.getDate();
    var dayOfTheWeek = date.getDay();
    var newDate = date.setDate(today - (dayOfTheWeek || 7));

    var dataFinal = new Date(newDate);

    return dataFinal;
}
  • 1

    It has to be a manual solution like Voce is doing or you accept use of some library to help answer?

3 answers

5

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>

  • very good your answer, but unfortunately I still can not use libraries in my project, but in the future, if you need to use, it will be very interesting. Thank you :)

2


var data = new Date('2020-12-25T00:00:00');

// O primeiro dia é o dia do mês, menos o dia da semana
var primeiro = data.getDate() - data.getDay(); 
 
primeiroDia = new Date(data.setDate(primeiro)).toUTCString();
ultimoDia = new Date(data.setDate(data.getDate()+6)).toUTCString();

console.log(primeiroDia)
console.log(ultimoDia)

  • Thanks @Rodrigo Zem!! Your example worked and the script became simple. :)

2

var dataAtual = new Date(); // obtem data atual
var primeiro = dataAtual.getDate() - dataAtual.getDay(); // Obtem primeiro dia da semana atual
var ultimo = primeiro + 6; // Primeiro dia da semana + 6

var primeiroDiaDaSemana = new Date(dataAtual.setDate(primeiro)).toUTCString();
var ultimoDiaDaSemana = new Date(dataAtual.setDate(ultimo)).toUTCString();

console.log(primeiroDiaDaSemana)
console.log(ultimoDiaDaSemana)

  • ops was wrong, I had taken an example in English and translated the variables, I let that escape, but the right is "dataAtual" instead of "Curr"

  • thanks for the help! There is a bug in the line "var ultimo = primeiroDiaDaSemana + 6;" where it should be "var ultimo = first + 6;". Apart from this bug, your example worked 100%. Thank you :)

  • ah yes, I corrected here, it’s the same situation same as Curr

Browser other questions tagged

You are not signed in. Login or sign up in order to post.