Inizio della settimana di lunedì con isoWeekday ()


117

Sto creando un calendario in cui stampo le settimane in formato tabellare. Un requisito è che io possa iniziare le settimane il lunedì o la domenica, secondo alcune opzioni dell'utente. Sto attraversando un periodo difficile utilizzando il metodo isoWeekday del momento .

// Start of some date range. Can be any day of the week.
var startOfPeriod = moment("2013-06-23T00:00:00"),

    // We begin on the start of the first week.
    // Mon Tues Wed Thur Fri Sat Sun
    // 20  21   22  23   24  25  26
    begin = moment(startOfPeriod).isoWeekday(1); // will pull from user setting

console.log(begin.isoWeekday()); // 1 - all good

// Let's get the beginning of this first week, respecting the isoWeekday
begin.startOf('week');

console.log(begin.isoWeekday()); // 7 - what happened ???

// Get column headers
for (var i=0; i<7; i++) {
    console.log(begin.format('ddd')); // I want Monday first!
    begin.add('d', 1);
}

jsFiddle

EDIT Ho frainteso quello che isoWeekdaystava effettivamente facendo. Ho pensato che impostasse la variabile "quale giorno della settimana è il primo giorno della settimana" (che non esiste). Quello che in realtà fa è semplicemente cambiare il giorno della settimana, proprio come moment.weekday(), ma utilizza un intervallo 1-7 invece di 0-6.

Risposte:


247

prova a usare begin.startOf('isoWeek');invece dibegin.startOf('week');


10
startOf('week')dipende dalla località in cui la domenica ovviamente segna l'inizio della settimana nel tuo caso. startOf('iweek')otterrà l'inizio ISO della settimana, che è lunedì. Ma hai ragione, non ho trovato alcuna documentazione sul sito ufficiale ...
devnull69

15
La versione corrente di moment.js sta utilizzando isoweek.
Savinger

2
Modificato in base al commento di @ savinger e ai documenti correnti :)
Matchu

20
isoWeek, con la W maiuscola, nell'ultima versione
Michiel

8
Documentato qui: Start of Time
Vladimir Kornea,

13

Chiama startOfprima isoWeekday.

var begin = moment(date).startOf('week').isoWeekday(1);

Demo funzionante


1
Questo non funziona correttamente. Per la data odierna, 05/09/2016, restituisce 29/08/2016 come data di inizio della settimana, il che non è vero, perché oggi è lunedì (settimana iso). la risposta corretta è già accettata.
undefinedman

9

In questo modo puoi impostare il giorno iniziale della settimana.

moment.locale('en', {
    week: {
        dow: 6
    }
});
moment.locale('en');

Assicurati di usarlo con moment().weekday(1);invece di moment.isoWeekday (1)


2

ho pensato di aggiungere questo per eventuali futuri capolini. Farà sempre in modo che il suo lunedì se necessario, può essere utilizzato anche per garantire sempre la domenica. Per me ho sempre bisogno del lunedì, ma il locale dipende dalla macchina utilizzata e questa è una soluzione semplice:

var begin = moment().isoWeekday(1).startOf('week');
var begin2 = moment().startOf('week');
// could check to see if day 1 = Sunday  then add 1 day
// my mac on bst still treats day 1 as sunday    

var firstDay = moment().startOf('week').format('dddd') === 'Sunday' ?     
moment().startOf('week').add('d',1).format('dddd DD-MM-YYYY') : 
moment().startOf('week').format('dddd DD-MM-YYYY');

document.body.innerHTML = '<b>could be monday or sunday depending on client: </b><br />' + 
begin.format('dddd DD-MM-YYYY') + 
'<br /><br /> <b>should be monday:</b> <br>' + firstDay + 
'<br><br> <b>could also be sunday or monday </b><br> ' + 
begin2.format('dddd DD-MM-YYYY');

1
possibile shortcut moment (). isoWeekday (1) .startOf ('isoweek'). format ('dddd DD MM YYYY')
davethecoder

2

Ecco una soluzione più generica per un dato giorno della settimana. Demo funzionante su jsfiddle

var myIsoWeekDay = 2; // say our weeks start on tuesday, for monday you would type 1, etc.

var startOfPeriod = moment("2013-06-23T00:00:00"),

// how many days do we have to substract?
var daysToSubtract = moment(startOfPeriod).isoWeekday() >= myIsoWeekDay ?
    moment(startOfPeriod).isoWeekday() - myIsoWeekDay :
    7 + moment(startOfPeriod).isoWeekday() - myIsoWeekDay;

// subtract days from start of period
var begin = moment(startOfPeriod).subtract('d', daysToSubtract);

-1

Per coloro che vogliono isoWeekessere il default puoi modificare il comportamento del momento come tale:

const moment = require('moment');
const proto = Object.getPrototypeOf(moment());

const {startOf, endOf} = proto;
proto.startOf = function(period) {
  if (period === 'week') {
    period = 'isoWeek';
  }
  return startOf.call(this, period);
};
proto.endOf = function(period) {
  if (period === 'week') {
    period = 'isoWeek';
  }
  return endOf.call(this, period);
};

Ora puoi semplicemente usare someDate.startOf('week')senza preoccuparti di ottenere domenica o dover pensare se usare isoweeko isoWeekecc.

Inoltre puoi memorizzarlo in una variabile come const period = 'week'e usarlo in sicurezza in subtract()o add()operations, ad es moment().subtract(1, period).startOf(period);. Questo non funzionerà con il periodo isoWeek.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.