Javascript 使用 Moment 获取 Date 对象的月份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38314717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Moment to get month of Date object
提问by NealR
I'm sure this is a simple thing but I haven't been able to find the specific syntax in any of the documentation or in any related posts.
我确信这是一件简单的事情,但我无法在任何文档或任何相关帖子中找到特定语法。
In order to get a month-picker to work i need to instantiate a new Date
object when my controller initializes.
为了让月份选择器工作,我需要Date
在我的控制器初始化时实例化一个新对象。
Controller
控制器
scope.date = new Date();
This creates a date object with the following format:
这将创建一个具有以下格式的日期对象:
Mon Feb 01 2016 15:21:43 GMT-0500 (Eastern Standard Time)
2016 年 2 月 1 日星期一 15:21:43 GMT-0500(东部标准时间)
However when I attempt to pull the month from the date object, using moment, I get the error:
但是,当我尝试使用 moment 从日期对象中提取月份时,出现错误:
enter code here
在此处输入代码
getMonth method
getMonth 方法
var month = moment().month(scope.date, "ddd MMM DD YYYY");
Any idea how to pull the month from the above date object without using substring?
知道如何在不使用子字符串的情况下从上述日期对象中提取月份吗?
回答by peteb
You can use moment.month()
it will return or set the value.
您可以使用moment.month()
它来返回或设置值。
moment.month()
is zero based, so it will return 0-11 when doing a get and it expects a value of 0-11 when setting passing a value in.
moment.month()
是基于零的,因此在执行 get 时它将返回 0-11,并且在设置传入值时期望值为 0-11。
var d = moment(scope.date);
d.month(); // 1
d.format('ddd MMM DD YYYY'); // 'Mon Feb 01 2016'
回答by Mawcel
As moment.month()
returns zero based month number you can use moment.format()
to get the actual month number starting from 1 like so
由于moment.month()
返回基于零的月份数,您可以使用它moment.format()
来获取从 1 开始的实际月份数,就像这样
moment.format(scope.date, 'M');
moment.format(scope.date, 'M');