简体   繁体   中英

moments how to get the last weekday of the last month(december)

i'm following this guide Get the First Weekday of the Month with moment.js

and it works fine to get the first weekday of the first month(January)

but, when i'm trying to use the opposite. i'm getting the last weekday of the month that will be December. i try to change the add in minus and sub but not working

 var dateFrom = moment().subtract(1, 'months').endOf('month').format("dddd")
alert(dateFrom);

For year use this

var year = moment().subtract(1, 'months').endOf('month').get('year');
alert(year);

use this with format "dddd".

So for business weekday use "moment-business" library .

working fiddle

You can use moment-business-days for doing business days related processing. It would be much easier if you are doing more of such processing and not just this problem.

var moment = require('moment-business-days');

// Set the date for december. You can use this for any month.
// Get array of business days for the month
var businessDays=moment('01-12-2017', 'DD-MM-YYYY').monthBusinessDays();

// Get last business day from the array
var lastBusinessDay = businessDays[businessDays.length-1]._d;

console.log(lastBusinessDay);

You can see the output here or clone and edit it. Here's the fiddle

/* 
    get last day of the year and add days:
    0   : if not sunday/saturday
    -2  : if sunday 
    -1  : if saturday 
*/
var eom = moment().utc().endOf('year');
eom.add((eom.day() % 6 !== 0) ? 0 : (eom.day() === 0) ? -2 : -1, 'day');

 /* Testing for every last week day of the month .. */ var eom = null; /* store end-of-month */ var log = ''; var i = 0; /* loop for all 12 months from jan - dec */ while (i < 12) { eom = moment().utc().month(i).endOf('month'); log = eom.format('LLLL') + ' ~~~ '; eom.add((eom.day() % 6 !== 0) ? 0 : (eom.day() === 0) ? -2 : -1, 'day'); log += eom.format('LLLL'); console.log(log); i++; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM