将每个月与一周中的正确日期对齐?

问题描述 投票:0回答:1

我正在创建一个日历应用程序,现在我正在努力让我的日子充满活力。

到目前为止,在后端,我有一个数组,它给出了每个月的天数。

const DaysInEachMonth = [
  moment('2017-01').daysInMonth(),
  moment('2017-02').daysInMonth(),
  moment('2017-03').daysInMonth(),
  moment('2017-04').daysInMonth(),
  moment('2017-05').daysInMonth(),
  moment('2017-06').daysInMonth(),
  moment('2017-07').daysInMonth(),
  moment('2017-08').daysInMonth(),
  moment('2017-09').daysInMonth(),
  moment('2017-10').daysInMonth(),
  moment('2017-11').daysInMonth(),
  moment('2017-12').daysInMonth()
];

在我的 ejs 文件中,我使用 DaysInEachMonth 循环天数。

<ul id="days">
<% for(var i = 0; i <= 11; i++) { %>
    <% var n = DaysInEachMonth[i] %>
    <% for(var j=1; j <= n; j++) { %>
      <li> <%= j %> </li>
      <% } %> 
<% } %>
</ul>

现在我遇到的问题是每个月的所有天都显示在一月下。我该如何做到这一点,以便每次我按下“下一个”按钮进入下个月时,我的日子也会改变。也许这不是最好的方法。任何帮助都会很棒,因为你可以看到我是 Node 新手。

javascript node.js express momentjs ejs
1个回答
1
投票

我必须同意@Alexus;这不是我个人会做的事情。

但要回答你的问题,

moment.js
有强大的方法来操纵日期。

例如,

moment#month(number|String)
可以更改月份。通过使用它,您可以像我在以下代码片段中所做的那样:

// Let's just set `nthMonth` to the 10th month for this example.
var nthMonth = 10;
// This gets the month November. (the tenth month when starting from 0)
var month = moment().month(nthMonth);
// This gets the amount of days in November
var daysInMonth = month.daysInMonth();
// Using the moment#format function, we can get a human-readable string from the date.
// By using the format 'MMMM', we only get the name of the month.
var monthName = month.format('MMMM')

console.log('Moment.JS Example:');
console.log('    Nth month:', nthMonth)
console.log('Name of month:', monthName)
console.log('Days in month:', daysInMonth)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

这也适用于您的代码。 StackOverflow 代码片段不支持 EJS,但我想你可以看到它是如何工作的:

// And just for your code:
var m = moment();
var days = $('#days');
for (var i = 0; i < 11; i++) {
  m.month(i);
  days.append(`<li class="month">${m.format('MMMM')}</li>`);

  var n = m.daysInMonth();
  for (var j = 1; j <= n; j++) {
    // We could use this code to show only the numbers.
    //days.append(`<li>${j}</li>`);
    // Or we use this code to make it a bit fancier.
    days.append(`<li>${m.date(j).format('dddd Do')}</li>`);
  }
}
#days > li {
  list-style-type: none;
}

.month {
  font-weight: bold;
  margin-top: .5em
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="days">
</ul>

© www.soinside.com 2019 - 2024. All rights reserved.