Momento js ottiene il primo e l'ultimo giorno del mese corrente


138

Come posso ottenere il primo e l'ultimo giorno e l'ora del mese corrente nel seguente formato in moment.js:

01/09/2016 00:00

Posso ottenere la data e l'ora correnti in questo modo: moment().format('YYYY-MM-DD h:m')che verranno visualizzate nel formato sopra.

Tuttavia, devo ottenere la data e l'ora del primo e dell'ultimo giorno del mese corrente, in qualche modo per farlo?

EDIT: La mia domanda è diversa da questa perché ciò richiede un determinato mese che l'utente ha già mentre sto chiedendo il mese corrente e chiedendo un formato specifico della data che non è menzionato nell'altro cosiddetto 'duplicato '.


2
Possibile duplicato dell'inizio e della fine
— Audite Marlow,

1
Moment.js supporta la funzione per ottenere il primo e l'ultimo giorno del mese, puoi ottenerlo per il mese corrente da: moment (). StartOf ('month') e moment (). EndOf ('month'). Penso che dovresti vedere la risposta da questo
— Tan Le

Sì, ma questo produce il seguente formato: Thu Sep 01 2016 00:00:00 GMT+0100 (GMT Summer Time)Voglio il formato come ho già detto nella mia domanda
— user3574492

Tale funzione restituisce l'oggetto momento per giorno, quindi puoi utilizzare il formato per l'output con qualsiasi formato desiderato. Come: moment (). StartOf ('month'). Format ('YYYY-MM-DD HH: mm').
— Tan Le

@AuditeMarlow Bel tentativo ma le domande sono leggermente diverse come spiegato nella mia modifica.
— user3574492

Risposte:


372

Nel caso in cui qualcuno abbia perso i commenti sulla domanda originale, è possibile utilizzare i metodi integrati (funziona a partire dal Momento 1.7):

const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
const endOfMonth   = moment().endOf('month').format('YYYY-MM-DD hh:mm');

1
Non so perché qualcuno abbia eliminato i commenti originali, ma il motivo per cui questa non era la risposta accettata è stato perché è stato pubblicato molti mesi dopo la risposta accettata.
— user3574492

2
grazie @ user3574492 non è un grosso problema, grazie per il chiarimento - se pensi che questa risposta sia la migliore, penso che sia possibile cambiarla con la risposta accettata, anche se è stata pubblicata in seguito.
— Ali Yazdani,

3
moment(1, "DD");tornerà il primo giorno del mese corrente
— Anil Vangari

35

Ci sarebbe un altro modo per farlo:

var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();

27

Puoi farlo senza moment.js

Un modo per farlo nel codice Javascript nativo:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

firstDay = moment(firstDay).format(yourFormat);
lastDay = moment(lastDay).format(yourFormat);

Questo produce il formato data predefinito Thu Sep 01 2016 00:00:00 GMT+0100 (GMT Summer Time)non nel formato desiderato:2016-09-01 00:00
— user3574492

1
Usa momento per formattare la data ... firstDay = moment (firstDay) .format ('MM / GG / AAAA'); lastDay = moment (lastDay) .format ('MM / GG / AAAA');
— Kevin Grosgojat,

1
e come ottenere startdatee enddatedel prossimo mese usando questa formula?
— alka vaghela,

28
"Puoi farlo senza moment.js" usa moment.js per formattare la data ...
— SteamFire

10

Supponendo che si stia utilizzando un Selettore intervallo di date per recuperare le date. Potresti fare qualcosa di simile per ottenere quello che vuoi.

$('#daterange-btn').daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            startDate: moment().subtract(29, 'days'),
            endDate: moment()
        }, function (start, end) {
      alert( 'Date is between' + start.format('YYYY-MM-DD h:m') + 'and' + end.format('YYYY-MM-DD h:m')}

9

moment startOf () ed endOf () è la risposta che stai cercando. Ad esempio: -

moment().startOf('year');    // set to January 1st, 12:00 am this year
moment().startOf('month');   // set to the first of this month, 12:00 am
moment().startOf('week');    // set to the first day of this week, 12:00 am
moment().startOf('day');     // set to 12:00 am today

1

Prima e ultima data del mese corrente In moment.js

console.log("current month first date");
    const firstdate = moment().startOf('month').format('DD-MM-YYYY');
console.log(firstdate);

console.log("current month last date");
    const lastdate=moment().endOf('month').format("DD-MM-YYYY"); 
console.log(lastdate); 

1

Come semplice possiamo usare daysInMonth () e endOf ()

const firstDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').startOf('month').format('D')
const lastDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').endOf('month').format('D')
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.