如何仅在工作时间增加计数器?

huangapple go评论60阅读模式
英文:

How can I increment a counter only for working hours?

问题

I'm trying to create a counter which increments +1 every minute. (Perfect will be around 70 value for one hour.)

But, the counter should start at 6 am and work until 8 pm (working hours), and Monday - Friday (working days). For weekends and outside working hours it should be paused, but it should show value counted. The next day it will continue from the last value.

Counter will stop at the end of the month, reset, 1st in month start again (if it's a working day).

function startCounter() {
    // 获取当前日期和时间
    var currentDate = new Date();
    var currentDay = currentDate.getDay(); // 0: 星期天, 1: 星期一, ..., 6: 星期六
    var currentHour = currentDate.getHours();

    // 检查是否是周末或非工作时间
    var isWeekend = currentDay === 0 || currentDay === 6; // 星期天或星期六
    var isOutsideWorkingHours = currentHour < 6 || currentHour >= 20; // 早于上午6点或晚于晚上8点

    // 如果是周末或非工作时间,暂停计数器
    if (isWeekend || isOutsideWorkingHours) {
        console.log('计数器暂停。');
        return;
    }

    // 获取计数器的启动日期
    var startingDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); // 当月的第一天

    // 计算自启动日期以来的天数,不包括周末
    var daysSinceStart = 0;
    for (var i = 0; i <= currentDay; i++) {
        if (i !== 0 && i !== 6) {
            daysSinceStart++;
        }
    }

    // 根据之前的天数计算计数器的初始值
    var initialValue = daysSinceStart * 1440; // 一天有1440分钟

    // 使用初始值初始化计数器
    var counter = initialValue;

    // 每分钟增加一次计数器
    var intervalId = setInterval(function () {
        counter++;
        console.log('计数器:', counter);
    }, 60000); // 60000毫秒 = 1分钟

    // 在页面刷新时显示计数器值
    console.log('计数器:', counter);
}

// 启动计数器
startCounter();

这里有什么遗漏的地方吗或者整个逻辑都需要更新吗

谢谢
英文:

I'm trying to create a counter which increments +1 every minute. (Perfect will be around 70 value for one hour.)

But, the counter should start at 6 am and work until 8 pm (working hours), and Monday - Friday (working days). For weekends and outside working hours it should be paused, but it should show value counted. The next day it will continue from the last value.

Counter will stop at the end of the month, reset, 1st in month start again (if it's working day)

function startCounter() {
// Get the current date and time
var currentDate = new Date();
var currentDay = currentDate.getDay(); // 0: Sunday, 1: Monday, ..., 6: Saturday
var currentHour = currentDate.getHours();
// Check if it&#39;s a weekend or outside working hours
var isWeekend = currentDay === 0 || currentDay === 6; // Sunday or Saturday
var isOutsideWorkingHours = currentHour &lt; 6 || currentHour &gt;= 20; // Before 6am or after 8pm
// If it&#39;s a weekend or outside working hours, pause the counter
if (isWeekend || isOutsideWorkingHours) {
console.log(&#39;Counter paused.&#39;);
return;
}
// Get the starting date for the counter
var startingDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); // 1st of the current month
// Calculate the number of days since the starting date, excluding weekends
var daysSinceStart = 0;
for (var i = 0; i &lt;= currentDay; i++) {
if (i !== 0 &amp;&amp; i !== 6) {
daysSinceStart++;
}
}
// Calculate the initial value of the counter based on the number of previous days
var initialValue = daysSinceStart * 1440; // 1440 minutes in a day
// Initialize the counter with the initial value
var counter = initialValue;
// Increment the counter every minute
var intervalId = setInterval(function() {
counter++;
console.log(&#39;Counter:&#39;, counter);
}, 60000); // 60000 milliseconds = 1 minute
// Display the counter value on page refresh
console.log(&#39;Counter:&#39;, counter);
}
// Start the counter
startCounter();

What I'm missing here? Or whole logic must be updated?

Thank you!

答案1

得分: 2

Here is the translated code portion:

好的
首先
如果你只计算工作小时如你所示一天只有14小时而不是24小时因此你应该添加的不是1440分钟而是840分钟每天但最好还是创建一些变量endHour和startHour以确保在任何地方都能正确计数
如果你希望即使不在工作时间内也要显示计数但在检查时不要返回计数
     
在你的代码中过去的天数计算不正确你假设一个月只有一周

而且你没有计算从一天开始经过了多少分钟
使用setInterval进行计数不是最好的主意但为了测试让它在这里

所以这是我的代码我对不同的开始时间和结束时间以及周末天数进行了测试

function startCounter() {
    // 获取当前日期和时间
    var currentDate = new Date();
    var currentDay = currentDate.getDay(); // 0:星期日,1:星期一,..., 6:星期六
    var currentHour = currentDate.getHours();
    var currentMinutes = currentDate.getMinutes();
    var currentDayOfMonth = currentDate.getDate();
    // 检查是否是周末或在工作时间之外
    var weekEndDays = [0,6]; // 周末 - 你可以添加或删除一些天
    var isWeekend = weekEndDays.indexOf(currentDay) > -1 ; // 是否是周末?
    var startHour = 6;
    var endHour = 20;
    var isOutsideWorkingHours = currentHour < startHour || currentHour >= endHour; // 在startHour之前或endHour之后?

    // 获取计数的起始日期
    var startingDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); // 当月的1号

    // 计算自起始日期以来的天数,不包括周末和当前日期
    var daysSinceStart = 0;
    for (let i = 1; i < currentDayOfMonth; i++) {
        let checkDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);

        if (checkDate.getDay() !== 0 && checkDate.getDay() !== 6) {
            daysSinceStart++;
        }
    }
    var minutesSinceStartOfDay = 0;

    // 如果今天是工作日,且工作时间已经结束,将其计算为已过的一天
    if (!isWeekend && isOutsideWorkingHours && currentHour >= endHour){
        daysSinceStart++;
    }
    // 如果是周末或在工作时间之外,显示“计数暂停”
    // 否则计算从工作日开始的分钟数,并显示“计数开始”
    if (isWeekend || isOutsideWorkingHours) {
        console.log('计数暂停。');
        //return;
    } else {
        minutesSinceStartOfDay = (currentHour - startHour)*60 + currentMinutes;
        console.log('计数开始...');
    }

    // 根据之前的天数计算计数器的初始值
     // 一天有(endHour-startHour)*60分钟
    // 用初始值初始化计数器
    var counter = daysSinceStart * (endHour-startHour)*60 + minutesSinceStartOfDay;

    // 每分钟递增计数器
    var intervalId = setInterval(function() {
        if (isWeekend || isOutsideWorkingHours) {
            console.log('计数器:', counter);
            return;
        }
        counter++;
        console.log('计数器:', counter);
    }, 60000); // 60000毫秒 = 1分钟

    // 刷新页面时显示计数器值
    console.log('计数器:', counter);
}

// 启动计数器
startCounter();

玩得开心
对我来说很有趣

Please note that I've provided the translated code portion as requested. If you have any specific questions or need further assistance with this code, feel free to ask.

英文:

Good day!
First of all:
If you counting only for working hours, as you show, there are only 14 hours per day, not 24. There for you will add not 1440, but 840 minutes per day. But better is to make couple of vars (endHour and startHour) to be sure to count correctly everywhere.
If you want to show counting even if not a work time, but not counting do not return when checking.

Counting past days in your code dosn't work. You counting as there is only one week in month.

And You not count how many minutes passed from start of the day.
Counting by setInterval is not the best idea, but let it be here for test.
So, here is my code, I tested it for different start- and endHours and weekEndDays:

function startCounter() {
// Get the current date and time
var currentDate = new Date();
var currentDay = currentDate.getDay(); // 0: Sunday, 1: Monday, ..., 6: Saturday
var currentHour = currentDate.getHours();
var currentMinutes = currentDate.getMinutes();
var currentDayOfMonth = currentDate.getDate();
// Check if it&#39;s a weekend or outside working hours
var weekEndDays = [0,6]; // weekend days - you can add or delete some days
var isWeekend = weekEndDays.indexOf(currentDay) &gt; -1 ; // Is a weekend?
var startHour = 6;
var endHour = 20;
var isOutsideWorkingHours = currentHour &lt; startHour || currentHour &gt;= endHour; // Before startHour or after endHour
// Get the starting date for the counter
var startingDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); // 1st of the current month
// Calculate the number of days since the starting date, excluding weekends and current day
var daysSinceStart = 0;
for (let i = 1; i &lt; currentDayOfMonth; i++) {
let checkDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);
if (checkDate.getDay() !== 0 &amp;&amp; checkDate.getDay() !== 6) {
daysSinceStart++;
}
}
var minutesSinceStartOfDay = 0;
// if today is working day, and work time is over, count it as fully passed day
if (!isWeekend &amp;&amp; isOutsideWorkingHours &amp;&amp; currentHour &gt;= endHour){
daysSinceStart++;
}
// If it&#39;s a weekend or outside working hours, show &#39;Counter paused.&#39;
// else count minutes from start of a working day and show &#39;Counter starting...&#39;
if (isWeekend || isOutsideWorkingHours) {
console.log(&#39;Counter paused.&#39;);
//return;
} else {
minutesSinceStartOfDay = (currentHour - startHour)*60 + currentMinutes;
console.log(&#39;Counter starting...&#39;);
}
// Calculate the initial value of the counter based on the number of previous days
// (endHour-startHour)*60 minutes in a day
// Initialize the counter with the initial value
var counter = daysSinceStart * (endHour-startHour)*60 + minutesSinceStartOfDay;
// Increment the counter every minute
var intervalId = setInterval(function() {
if (isWeekend || isOutsideWorkingHours) {
console.log(&#39;Counter:&#39;, counter);
return;
}
counter++;
console.log(&#39;Counter:&#39;, counter);
}, 60000); // 60000 milliseconds = 1 minute
// Display the counter value on page refresh
console.log(&#39;Counter:&#39;, counter);
}
// Start the counter
startCounter();

Have fun!
Was interesting for me.

huangapple
  • 本文由 发表于 2023年5月18日 00:15:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274168.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定