如何用moment.js找到日,月和年

vin*_*ini 61 javascript momentjs

2014-07-28

如何找到的month,yeardaymoment.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();
Run Code Online (Sandbox Code Playgroud)

hsz*_*hsz 94

试试:

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');
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

  • 请注意,所有这些值都是字符串,而不是您可能期望的数字 (2认同)

Chr*_*itz 90

我知道这已经得到了解答,但是我偶然发现了这个问题并沿着使用的路径前进format,这有效,但是当我想要整数时它会将它们作为字符串返回.

我刚刚意识到这个时刻的到来date,month以及year返回每个方法的实际整数的方法.

moment().date()
moment().month()
moment().year()
Run Code Online (Sandbox Code Playgroud)

  • `month()`是基于零的,而`date()`则不是.对于许多应用程序,你需要`moment().month()+ 1` (32认同)
  • 它不是.day()而是.date()来获取当月的当天. (7认同)

Sai*_*Ram 14

如果您正在寻找字符串值的答案,请尝试此操作

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


Vik*_*ngh 10

我得到day,monthyear使用专用的功能瞬间()日期() ,时刻()月()矩().今年()momentjs.

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);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

我不知道为什么@Chris Schmitz答案中有48个赞成,这不是100%正确.

月是数组的形式,从0开始,以获得我们应该使用的确切值 1 + moment().month()