如何使用moment.js查找日期、月份和年份

114

2014-07-28

如何在给定上述日期格式的情况下,使用 moment.js 找到 月份年份日期

var check = moment(n.entry.date_entered).format("YYYY/MM/DD");
var month = check.getUTCMonth();
var day = check.entry.date_entered.getUTCDate();
var year = check.entry.date_entered.getUTCFullYear();
5个回答

161

只需尝试:

var check = moment(n.entry.date_entered, 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

JSFiddle


3
请注意,所有这些值都是字符串而不是数字,这可能与您的预期不同。 - TroodoN-Mike
这个缺点是它将值转换为字符串。 - Andris

158
我知道这个问题已经有答案了,但我偶然看到这个问题并尝试使用format命令解决,虽然有效,但是它返回的是字符串而我需要整数。

我刚刚意识到,datemonthyear方法都有返回实际整数的功能。

moment().date()
moment().month()  // jan=0, dec=11
moment().year()

14
获取当前月份的日期应使用.date()而不是.day()。 - luiscvalmeida
52
month()的值是从0开始计数的,而date()的值不是。对于许多应用程序,您需要使用moment().month() + 1来获得正确的月份。 - 2Toad

30

如果您正在寻找字符串值的答案,请尝试以下方法

var check = moment('date/utc format');
day = check.format('dddd') // => ('Monday' , 'Tuesday' ----)
month = check.format('MMMM') // => ('January','February.....)
year = check.format('YYYY') // => ('2012','2013' ...)  

16

我正在使用 momentjs 的专用函数 moment().date()moment().month()moment().year() 来获取 daymonthyear

let day = moment('2014-07-28', 'YYYY/MM/DD').date();
let month = 1 + moment('2014-07-28', 'YYYY/MM/DD').month();
let year = moment('2014-07-28', 'YYYY/MM/DD').year();

console.log(day);
console.log(month);
console.log(year);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

我不知道为什么@Chris Schmitz的答案有48个赞,但并不完全正确。

月份以数组形式表示,从0开始计算,因此要获取准确值,我们应该使用1 + moment().month()


您传递的日期格式与您定义的格式不同。分隔符也不同。 - venimus

4

这里有一个你可以使用的例子:

 var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
  • dddd : 全称星期

  • Do : 月份中的第几天

  • MMMM : 全称月份

  • YYYY : 4位数年份

更多信息请参见:

https://flaviocopes.com/momentjs/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接