简体   繁体   English

如何使用 Vue.js 根据当前日期/时间设置时间间隔

[英]How can I set a time interval based on current date/time using Vue.js

Lets assume that current date/time is 03/29/2020 02:10 PM.假设当前日期/时间是 03/29/2020 02:10 PM。 Then i want to display 7 sets of time with fifteen minutes interval that will be 01:30 PM , 01:45 PM , 02:00 PM , 02:15 PM, 02:30 PM , 02:45 PM and 03:00 PM.然后我想显示 7 组时间,间隔为 15 分钟,分别是 01:30 PM、01:45 PM、02:00 PM、02:15 PM、02:30 PM、02:45 PM 和 03:00 PM .

Current Date/Time =  03/29/2020 02:10 PM

<div :key="timeList">
      <button>{{timeList}}</button>
</div>

How can i display seven sets of time in timeList as 15 minutes interval for currentTime as如何将 timeList 中的七组时间显示为 currentTime 的 15 分钟间隔

  • 01:30 PM 01:30 PM
  • 01:45 PM 01:45 PM
  • 02:00 PM 02:00 下午
  • 02:15 PM 02:15 PM
  • 02:30 PM 02:30 PM
  • 02:45 PM 02:45 PM
  • 03:00 PM 03:00 下午

If the current time is 02:10, then the next 15 minute block starts at 02:15.如果当前时间是 02:10,那么下一个 15 分钟的区块从 02:15 开始。

Anyway, you can use built–in formatting functions to get the appropriate format, eg无论如何,您可以使用内置的格式化函数来获取适当的格式,例如

 /* ** @param {Date} date: date to use for time blocks ** @param {number} mins: length of time block in minutes ** should be an even divisor of 60, eg 5, 10, 12, 15 ** @param {number} num: number of values to return ** @returns {Array} array of strings formatted as hh:mm ap */ function getTimes(date, mins, num) { // Copy date so don't affect original let d = new Date(date); // Get start of next block let dMins = d.getMinutes(); let nextMin = Math.ceil(dMins/mins) * mins; // If in first minute of first block, add 1 if (!(dMins%mins)) nextMin += mins; d.setMinutes(nextMin, 0, 0); let result = []; let opts = {hour:'2-digit', minute:'2-digit', hour12:true}; while (num--) { result.push(d.toLocaleString('en', opts)); d.setMinutes(d.getMinutes() + mins); } return result; } console.log(getTimes(new Date(), 15, 7));

I would recommend you use moment for this.我建议您为此使用moment Even though this can be done by adding little more lines using without moment , but adding moment to your project will save time and energy.尽管这可以通过使用 without moment添加更多行来完成,但是为您的项目添加moment将节省时间和精力。

<div id="app">
  <div v-for="item in timeList" :key="timeList">
      <button>{{item}}</button>
  </div>
</div>
<script>
new Vue({
  el: '#app',
  ...
  ...
  data: {
     timeList: [
     ],
  },
 mounted: function(){
   const current = new moment();
   for(let i=0;i<5;i++){
      this.timeList.push(current.format("HH:mm"));
      current.add(15, "minutes");
   }

 }
})
</script>

Check moment here https://momentjs.com/docs/在此处查看时刻https://momentjs.com/docs/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM