簡體   English   中英

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

[英]How to find the day, month and year with moment.js

2014-07-28

給定上面的日期格式,如何使用moment.js找到monthyearday

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();

只需嘗試:

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

我知道這已經得到了回答,但我偶然發現了這個問題,並沿着使用format的道路走下去,這可行,但是當我想要整數時,它會將它們作為字符串返回。

我剛剛意識到時刻帶有datemonthyear方法,這些方法返回每種方法的實際整數。

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

如果你正在尋找字符串值的答案,試試這個

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

我使用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 個贊成票,但不是 100% 正確。

月份是數組的形式,從 0 開始,所以為了得到確切的值,我們應該使用1 + moment().month()

這是您可以使用的示例:

 var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
  • dddd : 全天名稱

  • 做:一個月中的某一天

  • MMMM : 完整月份名稱

  • YYYY : 4 位數字年份

欲了解更多信息:

https://flaviocopes.com/momentjs/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM