【问题标题】:Time function that checks for certain days检查特定日期的时间函数
【发布时间】:2018-12-08 21:01:52
【问题描述】:

我有以下时间函数,用于输出业务是否开放或关闭。我对其进行编码的方式在正常工作周内运行良好。我想做的是为假期编程,比如圣诞节、7 月 4 日等总是在同一天,所以输出显示我们关闭了。

在固定假期我将如何编程?

function timeNow() {

    //Get time
    var d = new Date(),
    h = ('0' + d.getHours()).slice(-2),
    m = ('0' + d.getMinutes()).slice(-2);

    //Get Day
    new Date().getDay();
    var day = new Date().getDay();
    console.log(day);
    var operateDay = '';
    if (day >= 1 && day <= 5) {
        operateDay = true;
    } else if (day < 1 || day > 5) {
        operateDay = false;
    }

    // Checking time range
    var operatingTime = ((h >= 8 && h < 17) || (h === 8 && m == 0));
    var closedTime = (h >= 17 || h <= 8);
    var operateStatus = '';

    if ((operatingTime) && (operateDay = true)) {
        operateStatus = 'Our office is currently open';
        $('#closedWrap').addClass('block');
        $('#operationStatus').addClass('open');
    } else if (closedTime) {
        operateStatus = 'Our office is currently closed';
        $('#closedWrap').addClass('block');
        $('#operationStatus').addClass('closed');
    } else if (operateDay = false) {
        operateStatus = 'Our office is currently closed';
        $('#closedWrap').addClass('block');
        $('#operationStatus').addClass('closed');
    }

    return operateStatus;
}
var operation = timeNow();
$('#operationStatus').html(operation);

【问题讨论】:

  • 从概念上讲,我会想象一个强制关闭的天数数组,可能已经作为 Date 对象,然后您可以对该数组执行逻辑以检查日期是否为与任何数组日期相同。如果是这样,这个地方就关闭了。
  • @Taplar 我不知道如何指定一天。
  • 前。 new Date('07-01-2018') 是 7 月 1 日
  • @Taplar new Date('2018-07-01') 可能会产生更好的结果,而new Date(2018, 6, 1) 会得到最好的结果。
  • @MikeMcCaughan new Date('2018-07-01') 在控制台中的计算结果为 Sat Jun 30 2018,这让我感到惊讶,因为我认为 Date 会期望 ISO,但这就是我颠倒顺序的原因。

标签: javascript jquery function time


【解决方案1】:

我修改了您的原始函数并创建了初始版本,它处理自定义、易于“配置”、人类可读的特定假期列表。

/**
 * Returns the office's open/closed state.
 *
 * @param {Date} [time] - A custom Date object to override the current time.
 * @returns {string} The state of the office (open or closed).
 */
function timeNow(time) {
  // Holidays - month-day format, it's adjusted for human-readability, so
  // January is 1, February is 2 ... December is 12
  var holidays = [
    '01-01', // New Year's Day
    '07-04', // Independence Day,
    '11-11', // Veterans Day
    '12-25', // Chirstmas
    '12-31', // New Year's Eve
  ];
  
  // Possibility of overriding the current date, if needed
  time = time || new Date();

  // Get time
  var d = time,
    h = ('0' + d.getHours()).slice(-2),
    m = ('0' + d.getMinutes()).slice(-2);

  // Get day
  var day = time.getDay();
  var operateDay = '';
  if (day >= 1 && day <= 5) {
    operateDay = true;
  } else if (day < 1 || day > 5) {
    operateDay = false;
  }
  
  // Checking time range
  var operatingTime = ((h >= 8 && h < 17) || (h === 8 && m == 0));
  var closedTime = (h >= 17 || h <= 8);
  var operateStatus = '';

  // Check against holidays if the store is seemingly open  
  // Since in JavaScipt's built-in Date object, January is 0, February is 1 ... December is 11,
  // to be humanly usable, add 1 to it, hence the name "adjusted"
  var adjustedMonth = time.getMonth() + 1;
  var dayOfMonth = time.getDate();
    
  if (operatingTime) {
    for (var i = 0, len = holidays.length, holiday, holidayMonth, holidayDay; i < len; i++) {
      // Process the specific holiday month-date format
      holiday = holidays[i].split('-');
      holidayMonth = parseInt(holiday[0], 10);
      holidayDay = parseInt(holiday[1], 10);
      
      // Check, whether today is a holiday ...
      if (adjustedMonth === holidayMonth && dayOfMonth === holidayDay) {
        // ...and if it is, then ...Hooray! Hooray! It's a Holi-Holiday
        operatingTime = false;
        closedTime = true;
        break;
      }      
    }
  }

  if ((operatingTime) && (operateDay = true)) {
    operateStatus = 'Our office is currently open';
    $('#closedWrap').addClass('block');
    $('#operationStatus').addClass('open');
  } else if (closedTime) {
    operateStatus = 'Our office is currently closed';
    $('#closedWrap').addClass('block');
    $('#operationStatus').addClass('closed');
  } else if (operateDay = false) {
    operateStatus = 'Our office is currently closed';
    $('#closedWrap').addClass('block');
    $('#operationStatus').addClass('closed');
  }

  return operateStatus;
}

// Testing
var shouldBeOpen = [
  '2018-06-25',
  '2018-06-26',
  '2018-06-27',
  '2018-06-28',
  '2018-06-29'
];

var shouldBeClosed = [
  '2018-01-01',
  '2018-07-04',
  '2018-11-11',  
  '2018-12-25',  
  '2018-12-31',
  '2019-01-01'
];

var STATUS_OPEN = 'Our office is currently open';
var STATUS_CLOSED = 'Our office is currently closed';

// converts a human-readable year-month-day to UTC date
function strToUtcDate(string) {
  var parts = string.split('-');
  var year = parts[0];
  var month = parts[1];
  var day = parts[2];  
  return new Date(Date.UTC(year, month - 1, day, 12, 0, 0));
}

shouldBeOpen.forEach(function (string) {
  var date = strToUtcDate(string);
  var status = timeNow(date);
  
  if (status === STATUS_OPEN) {
    console.log('opened, as it should on:', date);
  } else {
    console.log('closed, BUT IT SHOULD NOT ON:', date);
  }
});

shouldBeClosed.forEach(function (string) {
  var date = strToUtcDate(string);
  var status = timeNow(date);
  
  if (status === STATUS_CLOSED) {
    console.log('closed, as it should on:', date);
  } else {
    console.log('opened, BUT IT SHOULD NOT ON:', date);
  }
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 谢谢理查德。这肯定有很大帮助。有没有办法通过将日期更改为 7-4 并实时运行来测试它?
  • 不客气!是的,当然,但我希望你的意思是在你的服务器上上演,而不是在生产中。在您想以任何方式部署它之前,请使用我修改过的源代码并创建一个有意义的单元测试套件。我很确定有 egde 情况,它会返回误报/误报。
  • 如何更改日期?因为,用你的代码更新了我的代码,但我认为我的输出只是读取我返回的函数return operateStatus; 来填充输出。你可以在这里查看:test.mbkit.com/test.mbkit.com/contact
  • 仅使用timeNow() 函数我已更改,而不是使用快速-n-脏测试的整个样本等等。首先在您自己的计算机上更改日期,但请为您自己编写一些适当的单元测试套件。
  • 好的,所以我只是取出了除了 timeNow() 函数之外的其他代码。如何手动更改日期以反映 7/4?我是时间/日期功能的新手。
猜你喜欢
  • 1970-01-01
  • 2012-05-27
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
  • 2014-08-26
相关资源
最近更新 更多