tra*_*ain 15 javascript jquery momentjs
我正在使用Moment.js,这很棒.我现在遇到的问题是,我无法弄清楚如何获得某个特定日期的月份.我只能在Moment js docs中找到"一年中的一周".例如,如果我选择今天的日期(2014年12月2日),我想知道这个日期是在本月的第二个星期,因此,它是本月的第二个星期三.有任何想法吗?
编辑:我想有些澄清是必要的.我最需要的是一个月中某一天的第n个数字.例如,(来自评论)2014年2月1日将是该月的第一个星期六.2014年2月3日将是本月的第一个星期一,尽管它在技术上是本月的第二周.基本上,谷歌日历的重复功能究竟是如何分类的.
Gio*_*rdo 30
似乎moment.js没有实现您正在寻找的功能的方法.但是,你可以找到使用一周的在一个月的某一天的第n个数量Math.ceil的date / 7
例如:
var firstFeb2014 = moment("2014-02-01"); //saturday
var day = firstFeb2014.day(); //6 = saturday
var nthOfMoth = Math.ceil(firstFeb2014.date() / 7); //1
var eightFeb2014 = moment("2014-02-08"); //saturday, the next one
console.log( Math.ceil(eightFeb2014.date() / 7) ); //prints 2, as expected
Run Code Online (Sandbox Code Playgroud)
看起来这是您正在寻找的数字,如以下测试所示
function test(mJsDate){
var str = mJsDate.toLocaleString().substring(0, 3) +
" number " + Math.ceil(mJsDate.date() / 7) +
" of the month";
return str;
}
for(var i = 1; i <= 31; i++) {
var dayStr = "2014-01-"+ i;
console.log(dayStr + " " + test(moment(dayStr)) );
}
//examples from the console:
//2014-01-8 Wed number 2 of the month
//2014-01-13 Mon number 2 of the month
//2014-01-20 Mon number 3 of the month
//2014-01-27 Mon number 4 of the month
//2014-01-29 Wed number 5 of the month
Run Code Online (Sandbox Code Playgroud)
小智 8
根据给定日期计算月中的星期时,您必须考虑偏移量.并非所有月份都在一周的第一天开始.
如果您想考虑这个偏移量,如果您正在使用时刻,可以使用类似下面的内容.
function weekOfMonth (input = moment()) {
const firstDayOfMonth = input.clone().startOf('month');
const firstDayOfWeek = firstDayOfMonth.clone().startOf('week');
const offset = firstDayOfMonth.diff(firstDayOfWeek, 'days');
return Math.ceil((input.date() + offset) / 7);
}
Run Code Online (Sandbox Code Playgroud)
简单使用moment.js
函数week_of_month(date){
前缀= [1,2,3,4,5];
返回前缀[0 | moment(date).date()/ 7]
}