Moment.js如何获得每月的一周? (Google日历样式) [英] Moment.js how to get week of month? (google calendar style)

查看:226
本文介绍了Moment.js如何获得每月的一周? (Google日历样式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Moment.js,它很棒.我现在遇到的问题是,我无法弄清楚如何获得某个日期的月份.我只能在Moment js文档中找到一年中的某周".例如,如果我选择今天的日期(2014年2月12日),我想知道这个日期是在2月的第二周,因此,它是该月的第二个星期三.有什么想法吗?

I am using Moment.js and it is great. The problem I have now is that I can't figure out how to get the week of the month a certain date is. I can only find "week of year" in the Moment js docs. For example, if I choose today's date (2/12/2014), I would like to know that this date is in the second week of this month of february and consequently, it is the second wednesday of the month. Any ideas?

我认为有必要作一些澄清.我最需要的是一个月中某天的第n个数字.例如,(根据评论)2014年2月1日将是该月的第一个星期六. 2014年2月3日将是该月的第一个星期一,即使从技术上讲是该月的第二个星期.基本上,谷歌日历的重复功能是如何对日期进行分类的.

I guess some clarification is necessary. What I need most is the nth number of a certain day in a month. For example, (from the comments) Feb 1, 2014 would be the first Saturday of the month. Feb 3, 2014 would be the first Monday of the month even though it is "technically" the second week of the month. Basically, exactly how google calendar's repeat function classifies days.

推荐答案

似乎moment.js没有实现所需功能的方法. 但是,您可以使用date / 7中的Math.ceil查找一个月中某天的第n个数字. 例如:

It seems that moment.js does not have the method that implements the functionality that you are looking for. However, you can find the nth number of a certain day of the week in a month is using the Math.ceil of the date / 7 For example:

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

这似乎是您要查找的电话号码,如以下测试所示

It looks like this is the number you are looking for, as demonstrated by the following test

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

这篇关于Moment.js如何获得每月的一周? (Google日历样式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆