Momento JS inizio e fine di un dato mese


94

Ho bisogno di calcolare una data JS dato anno = 2014 e mese = 9 (settembre 2014).

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 i registri mostrano:

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

La data di fine è corretta ma ... perché la data di inizio non lo è?

Risposte:


178

Questo perché endOfmuta il valore originale.

Preventivo pertinente:

Muta il momento originale impostandolo alla fine di un'unità di tempo.

Ecco una funzione di esempio che ti dà l'output che desideri:

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:


4
momentè idempotente quindi potresti anche usare endDate = moment(starDate).endOf("month") ^. ^
Grazie

1
Assolutamente sì, infatti il ​​modo predefinito per clonare un oggetto nella documentazione è moment(<value>). Aggiornato l'esempio per utilizzare alcune delle funzioni più brevi.
klyd

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

1
è la prima volta che vedo la parola idempotente usata sul web !! ben fatto naomik
Mike

add(-1,"month")non funziona quando è gennaio e vuoi ottenere il mese dell'anno scorso.
Akhoy

20

puoi usarlo direttamente per la data di fine o 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


16

Quando lo usi, .endOf()stai mutando l'oggetto su cui è chiamato, quindi startDatediventa il 30 settembre

Dovresti usarlo .clone()per farne una copia 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) 

5

Prova il codice seguente:

const moment=require('moment');
console.log("startDate=>",moment().startOf('month').format("YYYY-DD-MM"));
console.log("endDate=>",moment().endOf('month').format("YYYY-DD-MM"));

1
dovresti aggiungere un po 'di contesto con il tuo codice per spiegare perché e come risolverà il problema
ᴄʀᴏᴢᴇᴛ

3

Non credo 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'));

2

la tua data di inizio è il primo giorno del mese, in questo caso possiamo usare

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

Spero che questo ti aiuti!!


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>


0
const dates = getDatesFromDateRange("2014-05-02", "2018-05-12", "YYYY/MM/DD", 1);           
console.log(dates);
// you get the whole from-to date ranges as per parameters
var onlyStartDates = dates.map(dateObj => dateObj["to"]);
console.log(onlyStartDates);
// moreover, if you want only from dates then you can grab by "map" function

function getDatesFromDateRange( startDate, endDate, format, counter ) {
    startDate = moment(startDate, format);
    endDate = moment(endDate, format);

    let dates = [];
    let fromDate = startDate.clone();
    let toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
    do {
        dates.push({
            "from": fromDate.format(format),
            "to": ( toDate < endDate ) ? toDate.format(format) : endDate.format(format)
        });
        fromDate = moment(toDate, format).add(1, "day").clone();
        toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
    } while ( fromDate < endDate );
    return dates;
}

Nota, .clone () è essenziale in momentjs altrimenti sovrascriverà il valore. Sembra nel tuo caso.

È più generico, per ottenere un mucchio di date che cadono tra le date.


-1

Il codice seguente dovrebbe funzionare:

$('#reportrange').daterangepicker({
                startDate: start,
                endDate: end,
                ranges: {
                    'Hoy': [moment(), moment()],
                    'Ayer': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Ultimos 7 dias': [moment().subtract(6, 'days'), moment()],
                    'Ultimos 30 dias': [moment().subtract(29, 'days'), moment()],
                    'Mes actual': [moment().startOf('month'), moment().endOf('month')],
                    'Ultimo mes': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    'Enero': [moment().month(0).startOf('month') , moment().month(0).endOf('month')],
                    'Febrero': [moment().month(1).startOf('month') , moment().month(1).endOf('month')],
                    'Marzo': [moment().month(2).startOf('month') , moment().month(2).endOf('month')],
                    'Abril': [moment().month(3).startOf('month') , moment().month(3).endOf('month')],
                    'Mayo': [moment().month(4).startOf('month') , moment().month(4).endOf('month')],
                    'Junio': [moment().month(5).startOf('month') , moment().month(5).endOf('month')],
                    'Julio': [moment().month(6).startOf('month') , moment().month(6).endOf('month')],
                    'Agosto': [moment().month(7).startOf('month') , moment().month(7).endOf('month')],
                    'Septiembre': [moment().month(8).startOf('month') , moment().month(8).endOf('month')],
                    'Octubre': [moment().month(9).startOf('month') , moment().month(9).endOf('month')],
                    'Noviembre': [moment().month(10).startOf('month') , moment().month(10).endOf('month')],
                    'Diciembre': [moment().month(11).startOf('month') , moment().month(11).endOf('month')]
                }
            }, cb);

-2

Prova il codice seguente:

moment(startDate).startOf('months')
moment(startDate).endOf('months')

2
Benvenuto in Stack Overflow. Ci sono altre dieci risposte a questa domanda; sarebbe bene da parte tua spiegare perché il tuo è migliore o preferibile degli altri.
chb

non sta dando il previsto o / p
Shyam
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.