program tip

순간 js는 이번 달의 첫날과 마지막 날을 얻습니다.

radiobox 2020. 8. 31. 07:38
반응형

순간 js는 이번 달의 첫날과 마지막 날을 얻습니다.


moment.js에서 다음 형식으로 이번 달의 첫 번째와 마지막 날과 시간을 가져 오려면 어떻게해야합니까?

2016-09-01 00:00

다음과 같이 현재 날짜와 시간을 얻을 수 있습니다 moment().format('YYYY-MM-DD h:m'). 위의 형식으로 출력됩니다.

그러나 이번 달의 첫 번째와 마지막 날의 날짜와 시간을 가져와야합니다. 어떻게해야합니까?

편집 : 내 질문은 다른 그 특정 달을 요구하기 때문에이 요구하고있는 반면 사용자가 이미 가지고 일 현재 중복 '소위 다른 언급되지 않은 날짜의 특정 형식에 대한 요구와 함께 달 '.


누군가 원래 질문에 대한 의견을 놓친 경우 기본 제공 방법을 사용할 수 있습니다 (Moment 1.7부터 작동).

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

moment.js 없이도 할 수 있습니다.

네이티브 자바 스크립트 코드에서이 작업을 수행하는 방법 :

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);

이를 수행하는 다른 방법이 있습니다.

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

날짜 범위 선택기를 사용하여 날짜를 검색한다고 가정합니다. 원하는 것을 얻기 위해 뭔가를 할 수 있습니다.

$('#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')}

moment startOf ()endOf () 는 검색중인 답입니다. 예 :-

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

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); 

참고 URL : https://stackoverflow.com/questions/39267623/moment-js-get-first-and-last-day-of-current-month

반응형