栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Moment.js获取一个月中的天数列表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Moment.js获取一个月中的天数列表

这是一个可以解决问题的函数(不使用Moment,而仅使用普通Javascript):

var getDaysArray = function(year, month) {  var monthIndex = month - 1; # 0..11 instead of 1..12  var names = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];  var date = new Date(year, monthIndex, 1);  var result = [];  while (date.getMonth() == monthIndex) {    result.push(date.getDate() + "-" + names[date.getDay()]);    date.setDate(date.getDate() + 1);  }  return result;}

例如:

js> getDaysArray(2012,2)["1-wed", "2-thu", "3-fri", "4-sat", "5-sun", "6-mon", "7-tue", "8-wed", "9-thu", "10-fri", "11-sat", "12-sun", "13-mon", "14-tue","15-wed", "16-thu", "17-fri", "18-sat", "19-sun", "20-mon", "21-tue", "22-wed", "23-thu", "24-fri", "25-sat", "26-sun", "27-mon", "28-tue","29-wed"]

ES2015 +版本:

const getDaysArray = (year, month) => {  const monthIndex = month - 1  const names = Object.freeze(     [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ]);  const date = new Date(year, monthIndex, 1);  const result = [];  while (date.getMonth() == monthIndex) {    result.push(`${date.getDate()}-${names[date.getDay()]}`);    date.setDate(date.getDate() + 1);  }  return result;}

请注意,与问题中包含的示例输出不同,上述解决方案不会在10号之前将日期补零。使用ES2017 +可以轻松修复:

    result.push(`${date.getDate()}`.padStart(2,'0') + `-${names[date.getDay()]}`);

在旧版本的JS中执行此操作需要滚动您自己的零填充逻辑,这虽然不难,但也不是问题的重点。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448744.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号