2014-09-30 18 views
62

Devo calcolare una data JS data anno = 2014 e mese = 9 (settembre 2014).Moment JS inizio e fine di un determinato mese

ho provato questo:

var moment = require('moment'); 
var startDate = moment(year+'-'+month+'-'+01 + ' 00:00:00'); 
      var endDate = startDate.endOf('month'); 
      console.log(startDate.toDate()); 
      console.log(endDate.toDate()); 

Entrambi log mostrano:

Tue Sep 30 2014 23:59:59 GMT+0200 (CEST) 
Tue Sep 30 2014 23:59:59 GMT+0200 (CEST) 

data di fine è corretto, ma ... perché la data di inizio non è?

risposta

114

Questo perché endOf muta il valore originale.

Rilevante citazione:

muta il momento originario impostando fino alla fine di un'unità di tempo.

Ecco un esempio di funzione che ti dà l'output che si desidera:

function getMonthDateRange(year, month) { 
    var moment = require('moment'); 

    // month in moment is 0 based, so 9 is actually october, subtract 1 to compensate 
    // array is 'year', 'month', 'day', etc 
    var startDate = moment([year, month - 1]); 

    // Clone the value before .endOf() 
    var endDate = moment(startDate).endOf('month'); 

    // just for demonstration: 
    console.log(startDate.toDate()); 
    console.log(endDate.toDate()); 

    // make sure to call toDate() for plain JavaScript date type 
    return { start: startDate, end: endDate }; 
} 

Riferimenti:

+2

'momento' è idempotente in modo da poter usare anche' endDate = moment (starDate) .endOf ("month") '** ^.^ ** – naomik

+1

Assolutamente, infatti il ​​modo predefinito per clonare un oggetto nella documentazione è 'momento ()'. Aggiornato l'esempio per utilizzare alcune delle funzioni più brevi. – klyd

+0

Grazie. Ho passato due ore a cercare di capire perché non funzionava. – Leon

12

Quando si utilizza .endOf() si stanno mutando l'oggetto si chiama, in modo startDate diventa set 30

Si dovrebbe usare .clone() per fare una copia di esso, invece di cambiarlo

var startDate = moment(year + '-' + month + '-' + 01 + ' 00:00:00'); 
      var endDate = startDate.clone().endOf('month'); 
      console.log(startDate.toDate()); 
      console.log(endDate.toDate()); 

Mon Sep 01 2014 00:00:00 GMT+0700 (ICT) 
Tue Sep 30 2014 23:59:59 GMT+0700 (ICT) 
2

Don Penso davvero che ci sia un metodo diretto per ottenere l'ultimo giorno, ma potresti fare qualcosa del genere:

var dateInst = new moment(); 
/** 
* adding 1 month from the present month and then subtracting 1 day, 
* So you would get the last day of this month 
*/ 
dateInst.add(1, 'months').date(1).subtract(1, 'days'); 
/* printing the last day of this month's date */ 
console.log(dateInst.format('YYYY MM DD')); 
0

tua startDate è il primo giorno-di-mese, in questo caso possiamo usare

var endDate = moment(startDate).add(1, 'months').subtract(1, 'days'); 

Spero che questo aiuti !!

3

è possibile utilizzare questo direttamente per la finale o la data di inizio del mese

new moment().startOf('month').format("YYYY-DD-MM"); 
new moment().endOf("month").format("YYYY-DD-MM"); 

è possibile modificare il formato definendo un nuovo formato

+0

momento(). endOf ("mese"). format ("AAAA-GG-MM"); – Scholle

0
var d = new moment(); 
var startMonth = d.clone().startOf('month'); 
var endMonth = d.clone().endOf('month'); 
console.log(startMonth, endMonth); 

doc

0

const year = 2014; 
 
const month = 09; 
 

 
// months start at index 0 in momentjs, so we subtract 1 
 
const startDate = moment([year, month - 1, 01]).format("YYYY-MM-DD"); 
 

 
// get the number of days for this month 
 
const daysInMonth = moment(startDate).daysInMonth(); 
 

 
// we are adding the days in this month to the start date (minus the first day) 
 
const endDate = moment(startDate).add(daysInMonth - 1, 'days').format("YYYY-MM-DD"); 
 

 
console.log(`start date: ${startDate}`); 
 
console.log(`end date: ${endDate}`);
<script 
 
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"> 
 
</script>

Problemi correlati